TypeScript Tutorial · TypeScript Basics · Lesson 3 of 25

TypeScript Basic Types

Annotate variables with string, number, boolean, arrays and more — and let inference do the rest.

Type annotations

Add : type after a variable or parameter name:

Example 1Try it yourself
let username: string = "ada";
let age: number = 36;
let isAdmin: boolean = false;
let nothing: null = null;
let big: bigint = 9007199254740993n;
console.log(username, age, isAdmin, nothing, big);
// @ts-expect-error — Type 'string' is not assignable to type 'number'.
age = "thirty-six";

Output

ada 36 false null 9007199254740993n

Type inference

You rarely need annotations on variables — TypeScript infers the type from the value. Annotate function parameters and public APIs; let inference handle the rest:

Example 2Try it yourself
let count = 10;            // inferred: number
const lang = "TypeScript"; // inferred: "TypeScript" (a literal type)
const scores = [90, 85];   // inferred: number[]
count += 1;
console.log(typeof count, lang, scores);

Output

number TypeScript [ 90, 85 ]

const gives the narrowest type: const x = "hi" has the literal type "hi", while let y = "hi" is string.

Arrays and tuples

number[] (or Array<number>) is a list of numbers. A tuple is a fixed-length array with a type per position:

Example 3Try it yourself
const primes: number[] = [2, 3, 5, 7];
const names: Array<string> = ["Ada", "Lin"];
const point: [number, number] = [3, 4];
const entry: [string, number] = ["apples", 5];
const [label, qty] = entry;
console.log(primes.length, names.join(", "), point, `${label}=${qty}`);

Output

4 Ada, Lin [ 3, 4 ] apples=5

Test yourself

What type does TypeScript infer for const lang = "TS"?

  1. string
  2. "TS" (a literal type)
  3. any
  4. unknown
Show answer

Answer: "TS" (a literal type)