Skip to content
LumenaryAcademy
Foundations 55 min

Basic and literal types

Primitives, arrays and tuples, the special types any, unknown and never, and the literal types that make TypeScript precise.

Code tested · 4AI-draftedAwaiting review by a computer scientist
MotivationH

How precise can a type be?

A type is a set of values. number is a very large set; boolean has exactly two members; and TypeScript lets you go further and say "this value is exactly the string "north", "east", "south" or "west"", or "this is an array of exactly two numbers". The more precisely a type describes what a value can be, the more mistakes the compiler can catch, and the better your editor can help: type heading = " and it lists the four directions.

This lesson covers the building blocks: the primitive types you know from JavaScript, arrays and tuples, the three special types any, unknown and never, and literal types, which turn ordinary values into types. It ends with satisfies, a small operator that solves a surprisingly common problem.

Worked examplesH

Primitives, arrays and tuples

Each JavaScript primitive has a type of the same name, written in lowercase: string, number, boolean, bigint, symbol, null and undefined. (The capitalised String, Number and Boolean are the wrapper objects; never use them as types.) Arrays are written T[] or, equivalently, Array<T>.

typescript
// Primitive types, arrays and tuples: annotate where it helps, infer the rest.
const city: string = "Medellín";
const altitudeMetres: number = 1495;
const isCapital: boolean = false;
const population = 2_600_000;               // inferred: number
const bigCount: bigint = 2n ** 70n;

const temperatures: number[] = [22, 24, 23];
const sisterCities: Array<string> = ["Fort Lauderdale", "Bilbao"];
const frozen: readonly number[] = [1, 2, 3];

// A tuple: a fixed-length array whose positions have their own types.
const coordinates: [latitude: number, longitude: number] = [6.2442, -75.5812];
const [lat, lon] = coordinates;

// Optional and rest elements in tuples.
type Reading = [station: string, celsius: number, note?: string];
const readings: Reading[] = [["Poblado", 23.5], ["Bello", 21.0, "cloudy"]];

console.log(`${city}: ${altitudeMetres} m, capital: ${isCapital}, people: ${population}`);
console.log(bigCount, temperatures.length + sisterCities.length + frozen.length);
console.log(lat.toFixed(2), lon.toFixed(2));
for (const [station, celsius, note = "-"] of readings) {
  console.log(station.padEnd(8), celsius.toFixed(1), note);
}

export {};
text
Medellín: 1495 m, capital: false, people: 2600000
1180591620717411303424n 8
6.24 -75.58
Poblado  23.5 -
Bello    21.0 cloudy
  • Annotate or infer? The annotations on city, altitudeMetres and isCapital are redundant: TypeScript would infer the same types from the values, as it does for population. Idiomatic TypeScript annotates function parameters, return types of exported functions, and empty or ambiguous values (const ids: string[] = []), and lets inference do the rest.
  • readonly number[] is an array type without the mutating methods. Calling frozen.push(4) is an error: Property 'push' does not exist on type 'readonly number[]'. Use it for parameters you promise not to change; it costs nothing at run time.
  • Tuples such as [number, number] have a fixed length and a type per position. The labels in [latitude: number, longitude: number] are documentation only, but they appear in editor hints. A trailing ? makes an element optional. Reading past the end is an error: coordinates[2] gives Tuple type '[number, number]' of length '2' has no element at index '2'. Tuples are how TypeScript types functions that return several values, such as React's useState, which returns a [value, setter] pair. When the positions start to need names to be understood, switch to an object with named properties; a tuple of more than two or three elements is usually a sign that an object would read better.
  • type Reading = ... gives a type a name, a type alias. Lesson three compares aliases with interfaces.
Worked examplesH

null and undefined

In JavaScript, any variable can turn out to hold null or undefined, and reading a property of either throws. Tony Hoare, who introduced null references in 1965, later called them his "billion-dollar mistake". TypeScript's strict null checking (part of --strict) fixes this at the type level: null and undefined are separate types, and a variable may hold them only if its type says so, as in string | null or number | undefined.

typescript
// Under strict mode, null and undefined are separate types, never silently included.
const capitals = new Map([["Ghana", "Accra"], ["Peru", "Lima"], ["Nepal", "Kathmandu"]]);

function findCapital(country: string): string | undefined {
  return capitals.get(country);
}

const peru = findCapital("Peru");          // string | undefined
const atlantis = findCapital("Atlantis");  // string | undefined

console.log(peru?.toUpperCase(), atlantis?.toUpperCase());
console.log(peru ?? "unknown", atlantis ?? "unknown");
if (peru !== undefined) {
  console.log(peru.length);                // here TypeScript knows peru is a string
}

// A variable that may be empty on purpose: say so in its type.
let middleName: string | null = null;
console.log(middleName === null ? "no middle name" : middleName);
middleName = "Wanjiku";
console.log(middleName.length);            // narrowed by the assignment above

// Optional properties and parameters may be undefined.
function label(name: string, unit?: string): string {
  return unit === undefined ? name : `${name} (${unit})`;
}
console.log(label("altitude", "m"), "|", label("count"));

export {};
text
LIMA undefined
Lima unknown
4
no middle name
7
altitude (m) | count

Map.get returns string | undefined because the key might be missing, and so does findCapital. TypeScript then insists that you handle the undefined case before treating the result as a string: with optional chaining (peru?.toUpperCase()), a default (??), or a check (if (peru !== undefined)), after which the type is narrowed to string inside the block. Writing city.toUpperCase() without any of these is an error, 'city' is possibly 'undefined', and so is putting null where it is not declared: let n: number = null gives Type 'null' is not assignable to type 'number'. A parameter written unit?: string is optional, and inside the function its type is string | undefined.

There is an escape hatch: a postfix !, as in findCapital("Peru")!, is the non-null assertion, which tells the compiler "this is not null or undefined, trust me". It removes the error and checks nothing, so if you are wrong, the program fails at run time exactly as JavaScript would. Use it only where you know something the compiler cannot, and prefer a check that throws a clear error: if (city === undefined) throw new Error("no capital for Peru").

IntuitionH

Literal types

Definition— literal type

A literal type is a type with exactly one value: "north", 6, true. Combined with | into a union, literal types describe a fixed set of allowed values: "north" | "east" | "south" | "west".

typescript
// Literal types: a type with exactly one value, and unions of them.
type Direction = "north" | "east" | "south" | "west";
type DiceRoll = 1 | 2 | 3 | 4 | 5 | 6;

function turnRight(d: Direction): Direction {
  const order: Direction[] = ["north", "east", "south", "west"];
  return order[(order.indexOf(d) + 1) % order.length];
}

let heading: Direction = "north";
heading = turnRight(heading);
heading = turnRight(heading);
console.log(heading);

const roll: DiceRoll = 6;
console.log(roll, typeof roll);

// const infers the literal type; let widens it to the general type.
const fixed = "east";          // type "east"
let changeable = "east";       // type string
changeable = "anything at all";
console.log(fixed, changeable);

// as const: the narrowest, read-only type for a whole literal.
const SIZES = ["small", "medium", "large"] as const;   // readonly ["small", "medium", "large"]
type Size = (typeof SIZES)[number];                    // "small" | "medium" | "large"
const isSize = (s: string): s is Size => (SIZES as readonly string[]).includes(s);
console.log(SIZES.length, isSize("medium"), isSize("huge"));

// satisfies: check a value against a type without losing its precise type.
type Theme = Record<string, `#${string}`>;
const palette = {
  sky: "#87ceeb",
  sand: "#c2b280",
} satisfies Theme;
console.log(palette.sky.toUpperCase(), Object.keys(palette));

export {};
text
south
6 number
east anything at all
3 true false
#87CEEB [ 'sky', 'sand' ]

The compiler rejects anything outside the set. This file (declare function states that a function exists without giving its body, which is all the checker needs):

typescript
type Direction = "north" | "east" | "south" | "west";
type DiceRoll = 1 | 2 | 3 | 4 | 5 | 6;
declare function turnRight(d: Direction): Direction;

let heading: Direction = "up";
const roll: DiceRoll = 7;
let d = "east";
turnRight(d);

gives:

text
main.ts(5,5): error TS2322: Type '"up"' is not assignable to type 'Direction'.
main.ts(6,7): error TS2322: Type '7' is not assignable to type 'DiceRoll'.
main.ts(8,11): error TS2345: Argument of type 'string' is not assignable to parameter of type 'Direction'.

The third error surprises everyone once. Widening: a const can never change, so const fixed = "east" gets the literal type "east"; a let might be reassigned to any string, so let d = "east" is inferred as plain string, and a string is not a Direction. The fixes are to annotate (let d: Direction = "east") or to use const.

as const asks for the narrowest possible type for a whole expression: string and number literals keep their literal types, arrays become read-only tuples, and object properties become readonly. Here SIZES becomes readonly ["small", "medium", "large"]. Then (typeof SIZES)[number] (the type of any element of SIZES) is the union "small" | "medium" | "large". This pattern lets one list serve both as run-time data (to loop over, or to validate input against) and as a type, with no chance of the two drifting apart. (s is Size in isSize is a type predicate, covered in lesson four.)

Unions of literals instead of enums

TypeScript also has enum, which looks convenient: enum Direction { North, East, South, West }. But it is one of the few TypeScript features that generates run-time code, numeric enums accept any number without complaint, and they cannot be run by type-stripping tools such as Node's. Most modern code bases prefer a union of string literals, with an as const array or object when the values are also needed at run time. You will still meet enums in older code and some frameworks; read the handbook page linked above when you do.

DefinitionsH

any, unknown, never and void

Definition— any, unknown, never, void

any turns type checking off for a value: anything can be assigned to it, and it can be used in any way. unknown also accepts any value, but allows almost nothing to be done with it until its type has been checked. never is the empty type, with no values at all: the return type of a function that never returns normally, and the type of code that cannot be reached. void is the return type of a function whose result should be ignored.

typescript
// any switches checking off; unknown keeps it on until you check.
const fromJson: unknown = JSON.parse('{"temp": 21.5, "unit": "C"}');

// With unknown, you must find out what you have before you use it.
function describe(value: unknown): string {
  if (typeof value === "number") return `a number: ${value.toFixed(1)}`;
  if (typeof value === "string") return `a string of length ${value.length}`;
  if (Array.isArray(value)) return `an array of ${value.length}`;
  if (typeof value === "object" && value !== null) return `an object with keys ${Object.keys(value).join(", ")}`;
  return `something else: ${String(value)}`;
}

for (const v of [42, "hola", [1, 2], fromJson, null, undefined]) {
  console.log(describe(v));
}

// any is contagious: everything it touches is unchecked.
const loose: any = { temp: "21.5" };
const doubled = loose.temp * 2;          // no error, and doubled has type any
console.log(doubled, typeof doubled);

// never: the type with no values. A function that always throws returns never.
function fail(message: string): never {
  throw new Error(message);
}
try {
  fail("unreachable state");
} catch (err) {
  console.log((err as Error).message);
}

export {};
text
a number: 42.0
a string of length 4
an array of 2
an object with keys temp, unit
something else: null
something else: undefined
43 number
unreachable state

Inside describe, each typeof test narrows value from unknown to a specific type for the rest of that branch, which is why value.toFixed(1) is allowed after typeof value === "number". Using an unknown value without such a check is an error: fromJson.temp gives 'fromJson' is of type 'unknown'. That is exactly what you want for data from outside the program.

any is the opposite. loose.temp * 2 compiles even though temp is a string, and the result is any too, so the lack of checking spreads to everything computed from it. Here JavaScript's coercion happens to produce the number 43; with + it would have concatenated. Use unknown for values whose type you don't know yet, and keep any for the rare emergency, ideally with a comment explaining why. Strict mode's noImplicitAny makes sure any never appears silently: an unannotated parameter whose type cannot be inferred is an error rather than an unchecked any.

A catch clause's error variable is unknown under --strict (anything can be thrown in JavaScript), so err.message must be checked or asserted, as the last lines do with err as Error. Lesson four shows the safer err instanceof Error test.

ExplanationH

Type assertions, and when they are justified

You have now seen three ways to override the checker: as T, the non-null !, and any. They exist because sometimes you genuinely know more than the compiler: you just created an element with a known tag, a test has already established a fact the checker cannot follow, or a library's types are wrong. But each is a promise the compiler cannot verify, and a broken promise surfaces as a run-time bug far from the line that made it.

TypeScript does refuse assertions that are obviously impossible. In this file:

typescript
const port = "8080" as number;
const forced = "8080" as unknown as number;

the first line is rejected:

text
main.ts(1,14): error TS2352: Conversion of type 'string' to type 'number' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.

and the second, the "double assertion" through unknown, compiles, which is exactly why it should alarm anyone reviewing the code: forced is typed as a number but holds a string. An assertion never converts anything; to turn "8080" into a number you still write Number("8080").

The working rules most teams follow: prefer a check that narrows (typeof, instanceof, === undefined, covered in lesson four) to an assertion; use satisfies rather than as when you only want to check a shape; confine unavoidable assertions to a small, well-named function, so that the rest of the code base stays honest; and let a linter (typescript-eslint, lesson nine) flag any and needless assertions in review.

ExplanationH

satisfies: check without forgetting

Look again at palette in the literal-types program. There are two ways to say it should be a Theme, a record of colour names to strings starting with #, and they behave differently:

typescript
type Theme = Record<string, `#${string}`>;
const palette = { sky: "#87ceeb" } satisfies Theme;
const annotated: Theme = { sky: "#87ceeb" };
palette.ocean;
annotated.ocean;
text
main.ts(4,9): error TS2339: Property 'ocean' does not exist on type '{ sky: "#87ceeb"; }'.

An annotation (annotated: Theme) makes the variable's type exactly Theme: any string key is allowed, so the typo annotated.ocean goes unnoticed, and the knowledge of which keys exist is lost. satisfies (TypeScript 4.9) checks that the value conforms to Theme, rejecting { sea: "blue" } with Type '"blue"' is not assignable to type '`#${string}`', but keeps the value's own precise type, so palette.ocean is caught. The type `#${string}` is a template literal type: any string that starts with #. Lesson eight builds more of them.

Use satisfies for configuration objects, lookup tables and route maps: anywhere you want both "this must have the right shape" and "remember exactly what is in it".

Common misconceptionsH

Common misconceptions

Misconception

"unknown and any are the same." Both accept every value. Only any lets you then use it without checks. unknown is the safe one: it forces you to narrow before you use.

Misconception

"as const freezes the object." It only changes the type to read-only literals. At run time the object is an ordinary, mutable object; use Object.freeze if you also need run-time protection.

Misconception

"I should annotate every variable." Redundant annotations add noise and can even make types less precise (annotating const x: string = "a" throws away the literal type). Annotate parameters, exported return types and empty values; let inference handle the rest.

Misconception

"The type {} means an empty object." It means "any value except null and undefined", so a string or a number fits it too, because they have properties. For "some non-primitive object" write object; for "an object with string keys and values of type T" write Record<string, T>; and avoid the capitalised Object type entirely.

Misconception

"A tuple is a different thing from an array at run time." A tuple is an ordinary JavaScript array; its fixed length and per-position types exist only in the checker.

Exercises

Exercises

When a question asks for a type, write it as TypeScript prints it in error messages and editor hints. Check your answers in the Playground by hovering over the names.

1. Basic and literal types

Warm-upComputational

What type does TypeScript infer for y in let y = "hi";?

2. Basic and literal types

CoreComputational

What type does TypeScript infer for const mixed = [1, "a"];? Write it as TypeScript prints it.

3. Basic and literal types

CoreComputational

What type does TypeScript infer for const pair = [1, "a"] as const;? Write it as TypeScript prints it.

4. Basic and literal types

CoreComputational

Given const SIZES = ["small", "medium", "large"] as const;, what is the type (typeof SIZES)[number]?

Choose one

5. Basic and literal types

CoreComputational

What does this program print?

type Reading = [station: string, celsius: number, note?: string];
const r: Reading = ["Kumasi", 29];
const [station, celsius, note = "no note"] = r;
console.log(`${station}|${celsius}|${note}`, r.length);
export {};

6. Basic and literal types

CoreComputational

Given declare const u: unknown; declare const a: any;, which lines compile under --strict? Choose all that apply.

Choose all that apply

7. Basic and literal types

Warm-upComputational

With type DiceRoll = 1 | 2 | 3 | 4 | 5 | 6;, which declarations compile? Choose all that apply.

Choose all that apply

Further reading and resources