Primitive and basic types

TypeScript · Essentials · 8 min

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), boolean
  • bigint for arbitrary-precision integers (10n) and symbol for unique keys
  • null and undefined, 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:

  • any switches checking off for a value — avoid it (more later).
  • void is the "return type" of a function that returns nothing useful.
  • object means "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
  • number covers integers and floats alike
  • Under strict mode, null/undefined must be allowed explicitly

Watch out for

  • Writing String or Number (wrapper object types) instead of string / number.

Check yourself

  1. With strict on, which declaration accepts the value null?
  2. What is the type of both 3 and 3.14 in TypeScript?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: www.typescriptlang.org/docs/handbook/2/everyday-types.html