Sub topic 2
The primitive types
This chapter covers the types for single, non-object values: string, number, boolean, bigint and symbol. It assumes you know basic JavaScript syntax, can run code with tsc or an editor that reports TypeScript errors, and know what a data type is. The earlier chapter on static typing explains why the compiler checks types at all. Here you learn what each primitive type contains and where the compiler's rules differ from what JavaScript allows at runtime.
What a primitive is
A primitive is a value that is not an object. It has no properties of its own and cannot be changed in place. JavaScript has seven primitive kinds: string, number, boolean, bigint, symbol, null and undefined. This chapter covers the first five. null and undefined get their own chapter because strictNullChecks changes how they behave.
Each primitive type is written in lowercase, and the compiler checks assignments against it:
const title: string = "Types";
const count: number = 3;
const done: boolean = false;
const big: bigint = 9007199254740993n;
const id: symbol = Symbol("id");With a type annotation, the compiler uses what you wrote. Without one, it infers the type from the initial value. You rarely need to annotate the examples above, because every initializer already tells the compiler the type.
string
A string holds text. Single quotes, double quotes and template literals all produce the same type:
const first = "Ada";
const last = 'Lovelace';
const full = `${first} ${last}`; // string
console.log(full.length); // 11
console.log(full.toUpperCase()); // ADA LOVELACEA template literal that interpolates a value always has type string, whatever the type of the interpolated value. The compiler does not stop you from interpolating an object, so ${someObject} produces [object Object] without any error.
number
JavaScript has one numeric type for integers and decimals, a 64-bit IEEE 754 floating-point value. TypeScript mirrors this with a single number type. There is no int or float.
const age: number = 36;
const price: number = 19.99;
const hex: number = 0xff;
const big: number = 1e21;
const notANumber: number = NaN;
const infinite: number = Infinity;NaN and Infinity are of type number. The compiler cannot tell you that a division will produce NaN, so number does not guarantee a usable value. Check with Number.isNaN() and Number.isFinite() when the input comes from outside your code.
Floating-point rounding applies as in JavaScript:
console.log(0.1 + 0.2); // 0.30000000000000004
console.log(Number.MAX_SAFE_INTEGER); // 9007199254740991
console.log(Number.MAX_SAFE_INTEGER + 2); // 9007199254740992 (wrong)Integers above Number.MAX_SAFE_INTEGER lose precision. That is the main reason bigint exists.
boolean
A boolean is true or false. TypeScript does not convert other types to boolean for you in annotations. A string or number is not assignable to boolean, even though it is allowed in an if condition:
const enabled: boolean = true;
const name = "Ada";
if (name) {
console.log("truthy check is allowed in a condition");
}
// const flag: boolean = name; // Error: Type 'string' is not assignable to type 'boolean'.
const flag: boolean = name.length > 0; // an explicit comparison produces a boolean
const forced: boolean = !!name; // double negation also worksbigint
A bigint holds an integer of any size. Write a literal with an n suffix, or call BigInt():
const a: bigint = 9007199254740993n;
const b = BigInt(10);
const sum = a + b; // bigint
console.log(sum.toString()); // 9007199254741003
console.log(7n / 2n); // 3n (integer division, no decimals)Two rules cause most errors:
- You cannot mix
bigintandnumberin arithmetic.1n + 1is a compile error here, and aTypeErrorat runtime in plain JavaScript. Convert one side explicitly withBigInt(x)orNumber(x). - Literals with the
nsuffix need a compilertargetofES2020or later. With an older target, the compiler reports that bigint literals are not available.
const quantity: number = 5;
const total = 10n * BigInt(quantity); // 50nBigInt(1.5) throws a RangeError at runtime, because a bigint must be a whole number. The compiler accepts the call because the parameter is typed as number.
symbol
A symbol is a unique value created by calling Symbol(). Two symbols are never equal, even with the same description:
const a = Symbol("id");
const b = Symbol("id");
console.log(a === b); // falseSymbols are mostly used as property keys that cannot collide with other keys. When you declare one with const, TypeScript gives it the more specific type unique symbol, which lets it be used as a reliable key in a type:
const tag: unique symbol = Symbol("tag");
const record = {
[tag]: "internal",
name: "visible",
};
console.log(record[tag]); // "internal"unique symbol is allowed only on const declarations and static readonly class properties. A let variable gets plain symbol.
Lowercase types, not wrapper objects
JavaScript also has built-in wrapper objects named String, Number, Boolean, BigInt and Symbol. TypeScript has types with those capitalized names too, and they describe the objects, not the primitives.
let good: string = "text";
let bad: String = "text"; // allowed, but almost never what you want
// good = bad; // Error: 'String' is not assignable to 'string'.
bad = good; // a primitive is assignable to its wrapper typeThe compiler treats string as assignable to String, but not the other way around. Annotating with the capitalized names causes confusing errors when you pass the value to code that expects the primitive. Always use the lowercase names.
Primitive literal types
Each primitive value also has a type of its own. The string "Ada" has the type "Ada", the number 3 has the type 3, and true has the type true. A const variable keeps this narrow type. A let variable widens to the general primitive type:
const mode = "dev"; // type "dev"
let level = "dev"; // type string
const limit = 10; // type 10
let retries = 10; // type numberThe next chapters build on this behavior, including literal widening and union types.
Checking primitives at runtime
Types are erased when the code compiles, so the runtime has no knowledge of your annotations. To check a primitive's kind, use typeof, which TypeScript understands for narrowing:
| Type | `typeof` result |
|---|---|
| `string` | `"string"` |
| `number` | `"number"` |
| `boolean` | `"boolean"` |
| `bigint` | `"bigint"` |
| `symbol` | `"symbol"` |
function kind(value: string | number | bigint): string {
if (typeof value === "string") {
return "text of length " + value.length;
}
if (typeof value === "bigint") {
return "big integer " + value.toString();
}
return "number " + value.toFixed(1);
}
console.log(kind("hi")); // text of length 2
console.log(kind(12n)); // big integer 12
console.log(kind(3)); // number 3.0Common errors
- Writing
Number,StringorBooleanin annotations. Use the lowercase names. - Assuming
numbermeans a whole number. Nothing in the type system checks for integers. - Adding a
bigintand anumberwithout converting one of them. - Expecting
NaNto be caught by the compiler. It is a validnumber. - Using a bigint literal while the
targetis belowES2020. - Assigning a string or number to a
booleaninstead of writing a comparison.
Exercise
This code fails to compile. Name both problems and fix them. const total: number = 10n + 5; and let label: String = "ready"; const upper: string = label;
Show answer
The first line mixes bigint and number, and 10n cannot be assigned to a number annotation. Make both sides the same kind: const total: bigint = 10n + BigInt(5); or const total: number = 10 + 5;. The second problem is the capitalized wrapper type: String is not assignable to string. Annotate with the lowercase type: let label: string = "ready";, and the assignment to upper then compiles.