TypeScript Types Quick Reference
The type-system features you actually use — unions, generics, utility types, narrowing, and the syntax that trips people up.
TypeScript checks JavaScript at compile time and then erases the types, so almost nothing on this sheet exists at runtime — enums and parameter properties are the notable exceptions. Types are structural: a value fits a type if it has the right shape, whatever it was declared as.
The model that unlocks the advanced rows: a type is a set of values. A union widens the set, an intersection narrows it, never is the empty set and unknown is everything. Narrowing is the compiler shrinking that set as your if checks run.
never is the empty set; any is not a set at all, just checking switched off.Building blocks
- Union / literal
type Dir = "n" | "s" | "e" | "w"- Interface vs type
- interface for object shapes (extendable); type for unions/aliases
- Optional / readonly
{ name?: string; readonly id: number }- Function type
type Fn = (a: number) => string- Array / tuple
number[]·[string, number]- A & B
- intersection: a value with every member of both types
- { [key: string]: number }
- index signature: any string key maps to a number, like
Record<string, number> - x satisfies T
- check a value against a type without widening it — exact keys and literals survive (4.9+)
- enum vs union
- prefer
"a" | "b": enums emit runtime code and are banned byerasableSyntaxOnly
Type operators
- keyof T
- union of the keys:
keyof Useris"id" | "name" | "tags" - typeof value
- in a type position, the type of a variable:
type Config = typeof config - T["id"] / T[number]
- indexed access: one property’s type / an array or tuple’s element type
- (typeof roles)[number]
- with an
as constarray: the union of its string values - { [K in keyof T]?: T[K] }
- mapped type: transform every property — this one is
Partial<T> - -readonly / -?
- mapped-type modifiers that strip
readonlyor optionality - as `get${Capitalize<K & string>}`
- key remapping inside a mapped type:
namebecomesgetName - `on${Capitalize<E>}`
- template literal type:
"click" | "focus"becomes"onClick" | "onFocus" - T extends U ? X : Y
- conditional type; over a union it distributes —
[T] extends [U]stops that - infer R
- capture part of a type in a conditional:
T extends Promise<infer R> ? R : T
Generics
- Generic function
function first<T>(xs: T[]): T { return xs[0]; }- Constraint
<T extends { id: number }>- Default
<T = string>- <K extends keyof T>
prop(obj, key): T[K]— only real keys allowed, and the result follows the key- Inference
- type arguments come from the call: write
first([1, 2]), notfirst<number>(…) - <const T>
- infer literal, readonly types from arguments, as if the caller wrote
as const(5.0+) - NoInfer<T>
- keep one parameter from widening
T; the other arguments decide it (5.4+)
Utility types
- Partial / Required
Partial<T>all optional ·Required<T>all required- Pick / Omit
Pick<T, "a" | "b">·Omit<T, "id">- Record
Record<string, number>— a keyed map- Return / Parameters
ReturnType<typeof f>·Parameters<typeof f>- Readonly / NonNullable
Readonly<T>·NonNullable<T>- Exclude / Extract
Exclude<"a" | "b", "a">is"b";Extractkeeps the matching members- Awaited<T>
- unwrap promises recursively:
Awaited<Promise<Promise<number>>>isnumber - InstanceType<typeof C>
- the instance type a class constructor produces
- Uppercase / Capitalize
- string-literal transforms; also
LowercaseandUncapitalize
Narrowing & escape hatches
- typeof / in / instanceof
if (typeof x === "string")narrows the type- Type guard
function isCat(a: Animal): a is Cat- Non-null assertion
el!.focus()— "trust me, not null" (use sparingly)- as const
const dirs = ["n","s"] as const— literal, readonly tuple- unknown vs any
- Prefer
unknown— forces a check before use;anydisables type-checking - switch (s.kind)
- discriminated union: a shared literal field narrows to the matching member in each case
- const x: never = s
- exhaustiveness check in
default— stops compiling when a member is unhandled - asserts x is string
- assertion function: after the call, TypeScript treats
xas narrowed - as unknown as T
- forces an assertion TypeScript rejects as unrelated — a red flag in review
- // @ts-expect-error
- suppress the next line’s error, and fail if there is none — safer than
@ts-ignore
Functions & classes
- Overloads
- several signatures above one implementation; callers only ever see the signatures
- (...rest: [number, boolean])
- rest parameters typed as a tuple — fixed count and order
- constructor(private x: number)
- parameter property: declares and assigns the field in one step
- private vs #private
privateis checked at compile time only;#fieldis enforced at runtime too- abstract class
- cannot be instantiated; subclasses must implement its
abstractmembers - readonly string[]
- no
pushorsplice— accept it in parameters you do not mutate - class C implements I
- checks the class against an interface; it adds no members or types by itself
tsconfig & modules
- "strict": true
- enables
strictNullChecks,noImplicitAnyand the rest — the baseline for new code - noUncheckedIndexedAccess
arr[i]andrecord[key]become possiblyundefined— catches missing keys- exactOptionalPropertyTypes
name?: stringno longer accepts an explicitundefined- import type { Foo }
- type-only import, erased from output — required for types under
verbatimModuleSyntax - erasableSyntaxOnly
- bans enums, namespaces and parameter properties so Node can strip types directly (5.8+)
- declare module "*.svg"
- type a non-TypeScript import;
.d.tsfiles describe code that exists elsewhere - tsc --noEmit
- type-check only — the usual CI step when a bundler does the compiling
Worked example: Validate JSON at the boundary, then let the types flow
JSON.parse returns any, which lets a typo or a changed API reach production unchecked. Annotate the result as unknown and narrow it once, at the edge:
type User = { id: number; name: string; tags: string[] };
function isUser(x: unknown): x is User {
return (
typeof x === 'object' && x !== null &&
'id' in x && typeof x.id === 'number' &&
'name' in x && typeof x.name === 'string' &&
'tags' in x && Array.isArray(x.tags)
);
}
const data: unknown = JSON.parse(text);
data.name; // error
if (isUser(data)) {
data.tags.join(', '); // ok: data is User here
}
type Patch = Partial<Omit<User, 'id'>>;
const p: Patch = { name: 'Bo', id: 3 }; // error
tsc --strict (5.9) reports exactly two errors, positions trimmed:
error TS18046: 'data' is of type 'unknown'.
error TS2353: Object literal may only specify known properties, and 'id' does not exist in type 'Partial<Omit<User, "id">>'.
unknownblocks use until checked. Withany,data.namewould compile and fail at runtime if the field were missing.innarrows. Since TypeScript 4.9,'id' in xadds the property tox’s type, so the guard needs no casts.- The guard is a promise. TypeScript trusts the
x is Usersignature without checking that the body proves it. This one never checks that each tag is a string; a schema library checks deeply and derives the type from the schema. - Derived types stay in sync.
Patchis computed fromUser, so a new field becomes patchable everywhere andidnever does.
Recipes
Model API states with a discriminated union
type Result<T> =
| { status: 'loading' }
| { status: 'error'; error: Error }
| { status: 'success'; data: T };
function render(r: Result<string[]>): string {
switch (r.status) {
case 'loading': return 'Loading…';
case 'error': return r.error.message; // narrowed to the error member
case 'success': return r.data.join(', '); // narrowed to the success member
default: {
const unreachable: never = r; // compile error if a status is added
return unreachable;
}
}
}Impossible states, such as data and error at once, cannot be expressed. Add a fourth status and every switch that lacks a case for it stops compiling.
Derive types from one source of truth
const ROLES = ['admin', 'editor', 'viewer'] as const;
type Role = (typeof ROLES)[number]; // "admin" | "editor" | "viewer"
const defaults = { theme: 'dark', pageSize: 20 };
type Settings = typeof defaults; // { theme: string; pageSize: number }
type SettingKey = keyof Settings; // "theme" | "pageSize"
function isRole(x: string): x is Role {
return (ROLES as readonly string[]).includes(x);
}The array is both the runtime list and the type, so they cannot drift apart. The cast in isRole is needed because includes on a readonly tuple of literals only accepts those literals.
Type a config object without losing its keys
type Route = { path: string; auth?: boolean };
const routes = {
home: { path: '/' },
admin: { path: '/admin', auth: true },
} satisfies Record<string, Route>;
routes.admin.path; // ok, with autocomplete
routes.contact; // error: property 'contact' does not exist
type RouteName = keyof typeof routes; // "home" | "admin"With an annotation instead (const routes: Record<string, Route>) the keys widen to string: typos compile and keyof gives string. satisfies checks the shape and keeps the literal keys.
A type-safe getter and a typed event map
function prop<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const id = prop({ id: 1, name: 'Ana' }, 'id'); // number
prop({ id: 1 }, 'nope'); // error: not a key
type Events = { click: { x: number; y: number }; key: { code: string } };
function on<E extends keyof Events>(event: E, handler: (payload: Events[E]) => void) {}
on('click', (p) => p.x); // p is { x: number; y: number }
on('key', (p) => p.code); // p is { code: string }The constraint K extends keyof T ties the key to the object, and the indexed access T[K] makes the return type follow whichever key the caller passes.
Turn on the strict flags that catch real bugs
{
"compilerOptions": {
"target": "es2022",
"module": "esnext",
"moduleResolution": "bundler",
"strict": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true,
"noImplicitOverride": true,
"verbatimModuleSyntax": true,
"skipLibCheck": true
}
}noUncheckedIndexedAccess finds the most real bugs and is the noisiest to adopt, so enable flags one at a time in an existing codebase. Set module explicitly: with verbatimModuleSyntax on a CommonJS default, every ESM export is an error.
When to use it, and when not
- Types for your code, runtime checks for everything else. Types vanish at compile time, so request bodies, JSON files, environment variables and third-party responses need a check that runs.
- A union before overloads. If one signature with
string | numberdescribes the function, use it. Overloads earn their place only when the return type depends on which input form was passed. - Generics when a type flows through.
<T>is right when the output type depends on the input type. A type parameter used once, in a single parameter, is justunknownwith extra steps. - Conditional and mapped types in libraries, sparingly in apps. They make good APIs; in application code a plain interface reads better and gives clearer errors.
- JSDoc plus
// @ts-checktype-checks a plain JavaScript file with no build step: a gentle first move for an existing codebase.
Trade-offs and limits
| Choice | Gain | Cost |
|---|---|---|
strict + extra flags | whole bug classes caught at compile time | migration noise in an existing codebase |
| Deep type-level code | APIs that infer everything | slower checks, unreadable error messages |
interface extends | cached by name; conflicting members are an error | object shapes only |
A & B | works on any types | recomputed on use; conflicting members quietly become never |
| Enums | a runtime object you can iterate | emitted code; banned under erasableSyntaxOnly |
any | unblocks you now | spreads: whatever it touches is unchecked too |
The deepest limit: a type is a claim, not a check. as User, a wrong guard and an outdated .d.ts all compile cleanly and fail at runtime.
Common mistakes
ason untrusted data.await res.json() as Useris an assertion, not a check. When the API changes, the code compiles and crashes later, far from the cause.- Expecting
Object.keysto return keys. It returnsstring[]on purpose: structural typing means an object may carry properties its type never mentions. - Trusting excess-property checks. Only a fresh object literal is checked for unknown keys.
const extra = { …, admin: true }; const u: User = extra;compiles. - Forgetting
typeof null.typeof x === "object"leavesnullin the type, sox.idstill errors understrictNullChecks. Addx !== null. - Reading
{}as “empty object”. The type{}accepts any non-nullish value,42and"hi"included. Useobjectfor any non-primitive andRecord<string, never>for a truly empty object.
Check yourself
Given type ToArr<T> = T extends any ? T[] : never, what is ToArr<string | number>? And with [T] extends [any]?
string[] | number[]: a conditional on a bare type parameter distributes over each union member. Wrapping both sides in a tuple stops that and gives (string | number)[].
What types are inferred for const a = ["a", 1] and const b = ["a", 1] as const?
(string | number)[] and readonly ["a", 1]. const only stops reassigning the variable; as const keeps the literals and the length and adds readonly.
Under noUncheckedIndexedAccess, what is the type of arr[0] for arr: string[], and of tup[0] for tup: [string, number]?
string | undefined for the array, plain string for the tuple: its length is known, so declared positions are never treated as missing.
Can you pass a string[] to a parameter typed readonly string[]? And a readonly string[] to one typed string[]?
Yes, then no. A mutable array can be used read-only, but the reverse fails (“The type 'readonly string[]' is 'readonly' and cannot be assigned to the mutable type 'string[]'”) because the function could push into an array its owner promised nobody would change.
Questions about TypeScript Types Cheat Sheet
What is the difference between type and interface in TypeScript?
Both can describe the shape of an object, and for that job they are nearly interchangeable. An interface can be extended with extends and can be reopened: two declarations with the same name merge, which is how libraries let you add fields to their types. A type alias cannot merge, but it can name anything, including unions, tuples, mapped and conditional types, which interfaces cannot express. A common convention is interface for public object shapes and classes to implement, and type for unions and computed types. Pick one style per codebase and stay consistent.
What is the difference between any and unknown?
Both accept any value, but they treat what comes next very differently. any switches type checking off: you can call methods, read properties and pass the value anywhere, and mistakes surface only at runtime. unknown is the type-safe counterpart: you can store and pass the value, but you cannot use it until you narrow it with a check such as typeof, instanceof, a type guard or schema validation. Use unknown for data from outside the program, such as JSON.parse results, API responses and caught errors, and reserve any for rare escape hatches.
What does the satisfies operator do in TypeScript?
satisfies, added in TypeScript 4.9, checks that a value matches a type without changing the type TypeScript infers for it. Writing const config: Config = ... widens the variable to Config, so specific literal values and exact keys are forgotten. Writing const config = ... satisfies Config still reports any mistake against Config, but keeps the narrower inferred type, so keyof typeof config gives the real keys and literal values stay literal. It is most useful for configuration objects, route tables and lookup maps, where you want validation and precise autocomplete at the same time.
What is a discriminated union in TypeScript?
It is a union of object types that all share one property with a different literal value in each member, such as status set to loading, error or success. Checking that property, usually in a switch or an if, tells TypeScript exactly which member you have, so inside each branch it allows only the fields that member really has. Combined with an exhaustiveness check that assigns the leftover value to never, adding a new member makes every switch that forgot to handle it fail to compile. They are the standard way to model states, events and messages.