TypeScript · Lesson 1

Types & Narrowing

unknown vs any, literal types, as const, satisfies, type guards, assertion functions and control-flow analysis.

6 min read

In short

  • Types are proven line by line by control flow
  • Use unknown at trust boundaries, not any
  • typeof, equality, in and instanceof narrow unions
  • value is T guards are trusted, so test them
  • as const and satisfies keep literal types

TypeScript's type checker is a flow-sensitive analyser: the type of a variable is not one fixed thing, it is whatever the checker can prove at that line. Mastering TypeScript starts with understanding that every if, return, throw and switch changes what is known.

unknown vs any

Both accept any value. The difference is what you may do with it afterwards.

▶ Try
function bad(x: any) {
  x.foo.bar();          // compiles, explodes at runtime
}
function good(x: unknown) {
  // x.foo;             // error: 'x' is of type 'unknown'
  if (typeof x === 'string') x.toUpperCase(); // fine after narrowing
}

any turns the checker off and is contagious: any.foo is any, and passing any to a typed parameter is never an error. unknown is the honest "I don't know yet" type: it is the top type, and you must narrow it before use. Use unknown for anything crossing a trust boundary: JSON.parse results, fetch(...).json(), catch (e) variables (useUnknownInCatchVariables is part of strict), message events and env vars.

Literal types and widening

▶ Try
let a = 'GET';            // string    (mutable binding, widened)
const b = 'GET';          // "GET"     (const binding, literal kept)
const req = { method: 'GET' }; // { method: string }: properties are mutable, so widened

Widening is why passing req to a function that expects { method: 'GET' | 'POST' } fails with Type 'string' is not assignable to type '"GET" | "POST"'. (fetch itself types method as string, so it never complains.) The fixes are an annotation, as const, or satisfies.

as const

as const makes a literal expression deeply readonly and keeps every literal type:

▶ Try
const LEVELS = ['debug', 'info', 'warn', 'error'] as const;
// readonly ["debug", "info", "warn", "error"]
type Level = (typeof LEVELS)[number]; // "debug" | "info" | "warn" | "error"

This is the idiomatic replacement for enum: a runtime array you can iterate and a derived union type, with a single source of truth.

satisfies

An annotation (const x: T = ...) checks the value and replaces its type with T, losing detail. satisfies T checks the value against T but keeps the inferred type:

▶ Try
type Route = { path: string; auth: boolean };

const annotated: Record<string, Route> = { home: { path: '/', auth: false } };
annotated.typo;      // no error: any string key is allowed

const routes = {
  home: { path: '/', auth: false },
  admin: { path: '/admin', auth: true },
} as const satisfies Record<string, Route>;
routes.typo;         // error: property 'typo' does not exist
routes.admin.path;   // type "/admin"

as const satisfies T is the go-to pattern for config objects, route tables and lookup maps: validated shape plus exact literal types.

Narrowing toolbox

▶ Try
function render(x: string | number | Date | string[] | null) {
  if (x === null) return 'null';               // equality narrowing
  if (typeof x === 'string') return x;          // typeof: string number bigint boolean symbol undefined object function
  if (typeof x === 'number') return x.toFixed(2);
  if (Array.isArray(x)) return x.join(',');     // built-in type guard
  return x.toISOString();                       // only Date is left
}
  • typeof x === 'object' is also true for null: always pair it with x !== null.
  • instanceof works for classes (including Error subclasses) but not across realms (iframes, workers) and not for interfaces or type aliases, which do not exist at runtime.
  • 'key' in obj narrows unions of object types: if ('swim' in pet) pet.swim(). Since TS 4.9, in also narrows a plain object to object & Record<'key', unknown>, which makes hand-written validation of unknown data much nicer.
  • Truthiness (if (x)) removes null | undefined, but also 0, '' and false. Prefer x != null when zero or empty strings are valid values.

User-defined type guards: x is T

When the built-ins are not enough, write a function whose return type is a type predicate:

▶ Try
interface User { id: number; name: string }

function isUser(value: unknown): value is User {
  return (
    typeof value === 'object' && value !== null &&
    'id' in value && typeof value.id === 'number' &&
    'name' in value && typeof value.name === 'string'
  );
}

const data: unknown = JSON.parse(body);
if (isUser(data)) data.name; // User

The compiler trusts the predicate; it does not check that your body actually proves it. A wrong guard is a lie that spreads, so test guards thoroughly. Guards compose well with array methods: items.filter(isUser) returns User[]. Since TS 5.5 the compiler also infers predicates for simple arrow functions such as x => x !== undefined.

Assertion functions: asserts x is T

An assertion function narrows by throwing instead of returning a boolean. Code after the call only runs if the assertion held:

▶ Try
function assertIsDefined<T>(value: T, name: string): asserts value is NonNullable<T> {
  if (value === undefined || value === null) throw new Error(`${name} is required`);
}

function handler(userId: string | undefined) {
  assertIsDefined(userId, 'userId');
  userId.toUpperCase(); // string
}

asserts condition (without is) narrows by whatever expression you pass: assert(typeof x === 'number'). Gotcha: an assertion function must be called through a reference with an explicit type annotation. A function declaration is fine, but const assert = (c: unknown): asserts c => ... must be declared as const assert: (c: unknown) => asserts c = ..., otherwise you get error TS2775.

Control-flow analysis gotchas

▶ Try
function f(input: string | null) {
  if (input === null) return;          // early return narrows the rest of the function
  const isLong = input.length > 10;    // aliased conditions are tracked (TS 4.4+)

  setTimeout(() => input.length);      // OK: a parameter that is never reassigned keeps its narrowing
  let label: string | null = null;
  label = input;
  setTimeout(() => label.length);      // OK since TS 5.4: created after the last assignment

  let current: string | null = input;
  queueMicrotask(() => current.length); // error: 'current' is possibly 'null'
  current = null;                        // ...because it is reassigned after the closure exists
}
  • Narrowing survives into callbacks only if the variable is const, or is never assigned after the callback is created. Otherwise the callback might run after the reassignment, so it sees the declared type. Copy to a const first.
  • TS does not reset property narrowing (if (obj.x !== undefined)) after an arbitrary function call, even though that call could mutate obj. That trade-off is deliberate (it would be unusable otherwise) but it is a real soundness hole.
  • switch (true) { case typeof x === 'string': ... } narrows since TS 5.3.

readonly and tuples

▶ Try
function sum(xs: readonly number[]) { /* xs.push is a compile error */ }
type Point = readonly [x: number, y: number];
const p: Point = [1, 2];

Accept readonly T[] in parameters: it promises you won't mutate the caller's array, and a mutable array is assignable to it (not the other way round). Note that readonly is shallow and compile-time only. For runtime immutability you need Object.freeze.

In real codebases

Side note
  • Boundary code (HTTP handlers, queue consumers, config loaders) takes unknown and narrows with guards or a schema library (zod, valibot). Internal code then trusts the types.
  • as casts are a smell outside tests and boundary helpers: they switch off exactly the checks this lesson is about. A guard or assertion function documents why the type is safe.
  • Lint rules worth knowing: no-explicit-any, no-unsafe-* (to catch any leaking from libraries) and switch-exhaustiveness-check.

Practise this lesson

In the app: a short video, 7 exercises checked by real tests and a 12-question concept check. Free with a GitHub account.

Open in the app