These are the building blocks every other type is made from.
TypeScript names the JavaScript primitives with lowercase type names:
string,number(all numbers, integers and floats alike),booleanbigintfor arbitrary-precision integers (10n) andsymbolfor unique keysnullandundefined, each a type with exactly one value
Write them in lowercase. String, Number and Boolean with a capital letter refer to the wrapper objects (new String("x")) and are almost never what you want.
You annotate a variable with a colon after its name: let count: number = 0. From then on the checker enforces it — count = "ten" is an error, and so is calling count.toUpperCase(). Methods and properties are known for each type, so the editor can autocomplete name. with string methods.
Arrays are written number[] (or Array<number>), and an object's shape is described by its properties: { id: number; title: string }. Both get their own lessons.
There are a few special types you will meet early:
anyswitches checking off for a value — avoid it (more later).voidis the "return type" of a function that returns nothing useful.objectmeans "any non-primitive value"; it is rarely precise enough to be useful.
With strict on, null and undefined are not part of other types: a string variable can never hold null unless you say so with string | null. This one rule eliminates the most common runtime error in JavaScript — reading a property of undefined.
Example
let title: string = "Dune";
let pages: number = 412;
let inStock: boolean = true;
let isbn: bigint = 9780441013593n;
let missing: undefined = undefined;
let tags: string[] = ["sci-fi", "classic"];
let book: { title: string; pages: number } = { title, pages };
// @ts-expect-error -- Type 'string' is not assignable to type 'number'
pages = "four hundred";
let maybe: string | null = null; // null must be allowed explicitly
maybe = "now a string";
console.log(title.toUpperCase(), book.pages, tags.length, inStock, isbn, missing, maybe);Remember
- Use lowercase
string,number,boolean,bigint,symbol numbercovers integers and floats alike- Under strict mode,
null/undefinedmust be allowed explicitly
Watch out for
- Writing
StringorNumber(wrapper object types) instead ofstring/number.