Sub topic 2
The primitive types
This chapter assumes you know JavaScript variables, functions, and objects, can run tsc, and have strict enabled in tsconfig.json. Primitive types are the simplest types in TypeScript. Every other type is built from them.
TypeScript has seven primitive types: string, number, boolean, bigint, symbol, undefined, and null. You write an annotation after the variable name to declare one:
const label: string = "Total";
const amount: number = 19.99;
const paid: boolean = true;
const fee: bigint = 5n;
const key: symbol = Symbol("key");
let missing: undefined = undefined;
let empty: null = null;
console.log(`${label}: ${amount}`);Most of the time you can leave these annotations out, because TypeScript infers them from the assigned value. The annotations matter when a variable is declared before it gets a value, or when you want the compiler to reject other types.
The number type covers both integers and floating-point values. It is a 64-bit float in JavaScript, so it cannot represent every large integer exactly. Use bigint for integers beyond Number.MAX_SAFE_INTEGER.
const safe: number = 9007199254740991; // largest exact integer as number
const exact: bigint = 9007199254740993n; // needs the n suffix> Callout: the n suffix on a bigint literal requires a target of ES2020 or later in tsconfig.json.
With strict enabled, null and undefined are separate types, and a variable typed string cannot hold null. The next chapter on unions shows how to allow several types at once.
Exercise
Why does const big: number = 9007199254740993n; fail to compile, and what type should you use instead?
Show answer
The literal is a bigint, so it is not assignable to number. Annotate the variable as bigint instead.