On this page

TypeScript Cheat Sheet

Quick reference for TypeScript utility types, generics, type guards, patterns, and common gotchas.


Versions (November 2026)

VersionReleasedWhat changed
7.0Jul 2026Native Go port of the compiler ("Project Corsa"), ~10x faster builds. Same typescript package and tsc command. No programmatic API / language-service plugins yet — Vue, Svelte, Astro, Angular templates and typescript-eslint still need 6.0 (@typescript/typescript6, binary tsc6). 7.1 is in beta.
6.0Mar 2026Last JS-based release. New defaults: strict: true, module: esnext, target = latest ES (es2025), types: [], noUncheckedSideEffectImports: true. Deprecates target: es5, moduleResolution: node/node10/classic, baseUrl, AMD/UMD/System, outFile, esModuleInterop: false — all errors in 7.0.
5.x2023–2025satisfies (4.9), const type params + standard decorators (5.0), using (5.2), NoInfer (5.4), inferred type predicates (5.5), --erasableSyntaxOnly (5.8), import defer (5.9)

Modern Syntax (5.x+)

satisfies — check a value without widening it

type Route = { path: string; method: 'GET' | 'POST' };

const routes = {
  home:  { path: '/',      method: 'GET' },
  login: { path: '/login', method: 'POST' },
} satisfies Record<string, Route>;

routes.home.method;   // type 'GET' (kept), and typos in keys/values are errors
// routes.missing;    // Error — a `: Record<string, Route>` annotation would have allowed it

const type parameters — infer literals without as const at the call site

function tuple<const T extends readonly unknown[]>(...xs: T): T { return xs; }
const t = tuple('a', 1);   // readonly ['a', 1]  (without const: (string | number)[])

NoInfer<T> — stop a parameter from widening inference (5.4+)

function createLight<C extends string>(colors: C[], initial?: NoInfer<C>) {}
createLight(['red', 'green'], 'red');    // OK
// createLight(['red', 'green'], 'blue'); // Error: 'blue' not in 'red' | 'green'

Inferred type predicates (5.5+)

const nums = [1, null, 2].filter(x => x !== null);   // number[] — no manual `x is number` needed

using / await using — deterministic cleanup (5.2+)

class TempFile implements Disposable {
  constructor(readonly path: string) {}
  [Symbol.dispose]() { fs.rmSync(this.path); }
}

async function work() {
  using file = new TempFile('/tmp/x');            // disposed when the block exits, even on throw
  await using conn = await pool.connect();        // needs [Symbol.asyncDispose]
}

Needs lib: ["esnext.disposable"] (or esnext) and a runtime with Symbol.dispose (Node 24+, or a polyfill).

Standard decorators (5.0+)

function logged<This, Args extends unknown[], R>(
  target: (this: This, ...args: Args) => R,
  ctx: ClassMethodDecoratorContext<This, (this: This, ...args: Args) => R>,
) {
  return function (this: This, ...args: Args): R {
    console.log(`→ ${String(ctx.name)}`);
    return target.call(this, ...args);
  };
}

class Service {
  @logged run() {}
  accessor count = 0;                             // auto-accessor (getter/setter pair)
}

TC39 decorators need no flag; experimentalDecorators is only for legacy frameworks (older Angular, NestJS, TypeORM).

Running TypeScript directly

node app.ts            # Node 22.18+/23.6+ strips types natively (no enums/namespaces/parameter properties)
npx tsx app.ts         # Full TS support incl. enums, watch mode: tsx watch app.ts
npx tsc --noEmit       # Type-check only (use in CI)

Set "erasableSyntaxOnly": true so the compiler rejects syntax Node's type stripping can't handle.


Utility Types

Built-in Utility Types

TypeDescriptionExample
Partial<T>All properties optionalPartial<User>
Required<T>All properties requiredRequired<Config>
Readonly<T>All properties readonlyReadonly<State>
Pick<T, K>Select propertiesPick<User, 'id' | 'name'>
Omit<T, K>Remove propertiesOmit<User, 'password'>
Record<K, V>Object with typed keys/valuesRecord<string, number>
Extract<T, U>Extract union membersExtract<'a' | 'b' | 'c', 'a' | 'b'>
Exclude<T, U>Remove union membersExclude<'a' | 'b' | 'c', 'a'>
NonNullable<T>Remove null and undefinedNonNullable<string | null>
ReturnType<T>Function return typeReturnType<typeof fn>
Parameters<T>Function parameter typesParameters<typeof fn>
Awaited<T>Unwrap Promise typeAwaited<Promise<string>>
InstanceType<T>Class instance typeInstanceType<typeof MyClass>
ConstructorParameters<T>Constructor param typesConstructorParameters<typeof MyClass>
NoInfer<T>Block inference from this position (5.4+)initial?: NoInfer<C>
Uppercase / Lowercase / Capitalize / UncapitalizeString literal transformsCapitalize<'click'> → 'Click'
ThisParameterType<T> / OmitThisParameter<T>Inspect / strip this paramOmitThisParameter<typeof fn>

Usage Examples

interface User {
  id: number;
  name: string;
  email: string;
  role: 'admin' | 'user';
}

// Partial - for update payloads
function updateUser(id: number, data: Partial<User>) {}
updateUser(1, { name: 'Alice' }); // Only need some fields

// Pick - for specific views
type UserPreview = Pick<User, 'id' | 'name'>;

// Omit - for creation (no ID yet)
type CreateUser = Omit<User, 'id'>;

// Record - for lookup maps
type RolePermissions = Record<User['role'], string[]>;
const permissions: RolePermissions = {
  admin: ['read', 'write', 'delete'],
  user: ['read'],
};

Generics

Basic Generics

// Generic function
function identity<T>(value: T): T {
  return value;
}

// Generic with constraint
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}

// Generic interface
interface Repository<T> {
  findById(id: string): Promise<T | null>;
  save(entity: T): Promise<T>;
  delete(id: string): Promise<void>;
}

// Generic class
class TypedMap<K, V> {
  private map = new Map<K, V>();
  set(key: K, value: V): void { this.map.set(key, value); }
  get(key: K): V | undefined { return this.map.get(key); }
}

Generic Constraints

// Constrain to objects with id
function findById<T extends { id: string }>(items: T[], id: string): T | undefined {
  return items.find(item => item.id === id);
}

// Constrain to specific keys
function pick<T, K extends keyof T>(obj: T, keys: K[]): Pick<T, K> {
  const result = {} as Pick<T, K>;
  keys.forEach(key => { result[key] = obj[key]; });
  return result;
}

// Default generic type
interface ApiResponse<T = unknown> {
  data: T;
  status: number;
  message: string;
}

Advanced Generic Patterns

// Conditional types
type IsString<T> = T extends string ? true : false;

// Infer keyword
type UnwrapPromise<T> = T extends Promise<infer U> ? U : T;
type ArrayElement<T> = T extends (infer U)[] ? U : never;

// Mapped types
type Getters<T> = {
  [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};

// Template literal types
type EventName<T extends string> = `on${Capitalize<T>}`;
type ClickEvent = EventName<'click'>; // 'onClick'

Type Guards

typeof Guards

function process(value: string | number) {
  if (typeof value === 'string') {
    // TypeScript knows value is string here
    return value.toUpperCase();
  }
  // TypeScript knows value is number here
  return value.toFixed(2);
}

instanceof Guards

class ApiError extends Error {
  constructor(public statusCode: number, message: string) {
    super(message);
  }
}

function handleError(error: Error) {
  if (error instanceof ApiError) {
    // TypeScript knows error is ApiError
    console.log(error.statusCode);
  }
}

Custom Type Guards

interface Cat { meow(): void; }
interface Dog { bark(): void; }

// Type predicate function
function isCat(animal: Cat | Dog): animal is Cat {
  return 'meow' in animal;
}

function handleAnimal(animal: Cat | Dog) {
  if (isCat(animal)) {
    animal.meow(); // TypeScript knows it's a Cat
  } else {
    animal.bark(); // TypeScript knows it's a Dog
  }
}

Discriminated Unions

// The "type" field is the discriminant
type Shape =
  | { type: 'circle'; radius: number }
  | { type: 'rectangle'; width: number; height: number }
  | { type: 'triangle'; base: number; height: number };

function area(shape: Shape): number {
  switch (shape.type) {
    case 'circle':
      return Math.PI * shape.radius ** 2;
    case 'rectangle':
      return shape.width * shape.height;
    case 'triangle':
      return (shape.base * shape.height) / 2;
  }
}

// Exhaustive check helper
function assertNever(x: never): never {
  throw new Error(`Unexpected value: ${x}`);
}

Assertion Functions

function assertDefined<T>(value: T | null | undefined, msg?: string): asserts value is T {
  if (value === null || value === undefined) {
    throw new Error(msg ?? 'Value is not defined');
  }
}

function process(input: string | null) {
  assertDefined(input, 'Input required');
  // TypeScript knows input is string here
  console.log(input.toUpperCase());
}

Common Patterns

Builder Pattern

class QueryBuilder<T> {
  private filters: string[] = [];
  private sortField?: keyof T;

  where(field: keyof T, value: unknown): this {
    this.filters.push(`${String(field)} = ${value}`);
    return this;
  }

  orderBy(field: keyof T): this {
    this.sortField = field;
    return this;
  }

  build(): string {
    let query = `SELECT * FROM table`;
    if (this.filters.length) {
      query += ` WHERE ${this.filters.join(' AND ')}`;
    }
    if (this.sortField) {
      query += ` ORDER BY ${String(this.sortField)}`;
    }
    return query;
  }
}

Result Type (Error Handling)

type Result<T, E = Error> =
  | { ok: true; value: T }
  | { ok: false; error: E };

function ok<T>(value: T): Result<T, never> {
  return { ok: true, value };
}

function err<E>(error: E): Result<never, E> {
  return { ok: false, error };
}

// Usage
function divide(a: number, b: number): Result<number, string> {
  if (b === 0) return err('Division by zero');
  return ok(a / b);
}

const result = divide(10, 0);
if (result.ok) {
  console.log(result.value); // TypeScript knows it's number
} else {
  console.log(result.error); // TypeScript knows it's string
}

Branded Types

// Prevent mixing up primitive types
type UserId = string & { readonly __brand: unique symbol };
type OrderId = string & { readonly __brand: unique symbol };

function createUserId(id: string): UserId {
  return id as UserId;
}

function getUser(id: UserId): void {}
function getOrder(id: OrderId): void {}

const userId = createUserId('u123');
getUser(userId);  // OK
// getOrder(userId); // Error: UserId is not assignable to OrderId

Strict Event Emitter

type EventMap = {
  'user:login': { userId: string; timestamp: number };
  'user:logout': { userId: string };
  'error': { message: string; code: number };
};

class TypedEmitter<T extends Record<string, unknown>> {
  private handlers = new Map<string, Set<Function>>();

  on<K extends keyof T>(event: K, handler: (payload: T[K]) => void): void {
    if (!this.handlers.has(event as string)) {
      this.handlers.set(event as string, new Set());
    }
    this.handlers.get(event as string)!.add(handler);
  }

  emit<K extends keyof T>(event: K, payload: T[K]): void {
    this.handlers.get(event as string)?.forEach(h => h(payload));
  }
}

const emitter = new TypedEmitter<EventMap>();
emitter.on('user:login', (data) => {
  // data is typed as { userId: string; timestamp: number }
  console.log(data.userId);
});

Type Narrowing Techniques

TechniqueSyntaxNarrows To
typeoftypeof x === 'string'Primitive types
instanceofx instanceof DateClass instances
in'name' in xObjects with property
Discriminantx.type === 'a'Union members
Truthinessif (x)Non-nullish
Equalityx === nullSpecific value
Custom guardisFoo(x)Custom type
AssertionassertFoo(x)Custom type (throws)

Common Gotchas

Object vs object vs Record

// Object - almost anything (avoid)
let a: Object = 'string'; // works but useless

// object - any non-primitive
let b: object = {}; // OK
// let c: object = 'string'; // Error

// Record<string, unknown> - typed object (preferred)
let d: Record<string, unknown> = { key: 'value' };

Readonly Arrays

// Mutable array
const arr: number[] = [1, 2, 3];
arr.push(4); // OK

// Readonly array
const readonlyArr: readonly number[] = [1, 2, 3];
// readonlyArr.push(4); // Error

// as const makes deeply readonly
const config = {
  ports: [3000, 3001],
  host: 'localhost',
} as const;
// config.ports.push(3002); // Error
// config.host = 'other';   // Error

Enums vs Union Types

// Prefer union types over enums
// Bad: enum creates runtime code
enum Direction {
  Up = 'UP',
  Down = 'DOWN',
}

// Good: union type is zero-runtime
type Direction = 'UP' | 'DOWN';

// If you need enum-like objects, use as const
const Direction = {
  Up: 'UP',
  Down: 'DOWN',
} as const;
type Direction = typeof Direction[keyof typeof Direction];

Function Overloads

// Overload signatures
function parse(input: string): number;
function parse(input: string[]): number[];
// Implementation signature
function parse(input: string | string[]): number | number[] {
  if (Array.isArray(input)) {
    return input.map(Number);
  }
  return Number(input);
}

parse('42');     // returns number
parse(['1','2']); // returns number[]

The any Escape Hatches

// unknown is the safe alternative to any
function process(data: unknown) {
  // Must narrow before using
  if (typeof data === 'string') {
    console.log(data.toUpperCase());
  }
}

// never for exhaustive checks
type Shape = 'circle' | 'square';
function handle(shape: Shape) {
  switch (shape) {
    case 'circle': return;
    case 'square': return;
    default:
      const _exhaustive: never = shape;
      throw new Error(`Unhandled: ${_exhaustive}`);
  }
}

tsconfig.json Key Options

OptionRecommendedWhy
stricttrueEnables all strict checks (default since 6.0)
noUncheckedIndexedAccesstrueArray/object access returns T | undefined
exactOptionalPropertyTypestrueDistinguishes undefined from missing
noImplicitReturnstrueAll code paths must return
noFallthroughCasesInSwitchtruePrevent switch fallthrough
forceConsistentCasingInFileNamestruePrevent casing bugs on case-insensitive OS
skipLibChecktrueFaster builds, skip .d.ts checking
moduleResolutionbundler (apps with Vite/esbuild) or nodenext (Node libs/servers)node/node10 are deprecated in 6.0 and errors in 7.0
moduleesnext with bundler; nodenext with nodenextesnext is the 6.0 default
targetES2022 or newer (es2025 is the 6.0 default)Modern JS output; es5 is gone
verbatimModuleSyntaxtrueExplicit type imports
types["node"] (or what you use)Defaults to [] since 6.0 — global @types/* are no longer auto-included
erasableSyntaxOnlytrue if running via Node type strippingRejects enums, namespaces, parameter properties
isolatedModulestrueRequired by single-file transpilers (esbuild, swc, Babel)
paths (without baseUrl){"@/*": ["./src/*"]}baseUrl is deprecated in 6.0
// Minimal modern tsconfig for a Node 24 service
{
  "compilerOptions": {
    "target": "es2024", "module": "nodenext", "moduleResolution": "nodenext",
    "strict": true, "noUncheckedIndexedAccess": true, "verbatimModuleSyntax": true,
    "types": ["node"], "outDir": "dist", "rootDir": "src", "skipLibCheck": true
  },
  "include": ["src"]
}

When to Use X vs Y

DecisionChoice AChoice BUse A WhenUse B When
TypeinterfacetypeObject shapes, extendsUnions, intersections, mapped types
Assertionas TypeType guardYou are certain, one-offRuntime check needed, reusable
Null check! (non-null assertion)Proper null check100% certain, testingProduction code
Generic defaultT = unknownNo defaultLibrary API, optional genericInternal code
Importimport typeimportType only, no runtimeNeed the value at runtime
Typing a literalsatisfies T: T annotationKeep narrow literal types, still validateYou want the wider declared type
Cleanupusingtry/finallyResource implements Symbol.disposeOlder runtimes without the symbol
Compilertsc 7.xtsc6 / TS 6.0CLI builds, CI type-checksTools needing the TS API or LS plugins (Vue, Svelte, Angular templates, typescript-eslint)

Test Yourself
  1. What utility type makes all properties of a type optional? Partial<T>

  2. How do you create a type that picks only the id and name properties from User? Pick<User, 'id' | 'name'>

  3. What keyword extracts the inner type from a Promise<T> in a conditional type? infer (e.g., T extends Promise<infer U> ? U : T)

  4. How do you write a custom type guard function that checks if a value is a Cat? function isCat(animal: Cat | Dog): animal is Cat

  5. What is the zero-runtime alternative to TypeScript enums? Union types: type Direction = 'UP' | 'DOWN'

  6. What tsconfig option makes array/object indexing return T | undefined? noUncheckedIndexedAccess

  7. How do you get the return type of a function? ReturnType<typeof fn>

  8. What type should you use instead of any for safe unknown data? unknown -- it forces you to narrow the type before using it.

  9. What is a branded type used for? Preventing accidental mixing of primitive types that are structurally identical (e.g., UserId vs OrderId).

  10. What is the difference between interface and type in TypeScript? interface is best for object shapes and extends; type is best for unions, intersections, and mapped types.

  11. What does satisfies do that a type annotation doesn't? It checks the value against the type but keeps the value's own (narrower) inferred type.

  12. What changed in TypeScript 7.0? The compiler is a native Go port (~10x faster); options deprecated in 6.0 (node10 resolution, baseUrl, es5, …) are now errors, and there's no programmatic API yet.

Common Gotchas

  • Using any instead of unknown. any disables all type checking. Use unknown and narrow with type guards.
  • Non-null assertion ! in production code. It tells the compiler "trust me, this is not null" -- but at runtime it can absolutely be null. Use proper null checks.
  • Enums generate runtime code. Prefer union types (type Status = 'active' | 'inactive') for zero-runtime overhead.
  • Forgetting as const for literal types. Without it, const arr = [1, 2, 3] is typed as number[], not readonly [1, 2, 3].
  • Annotating instead of satisfies. const x: Record<string, Route> = {...} throws away the literal keys; satisfies keeps them.
  • Upgrading to 6.0/7.0 and losing globals. types now defaults to [], so process, describe, etc. disappear until you list "types": ["node", "vitest/globals"].
  • tsc file.ts with a tsconfig present errors (TS5112) since 6.0. Run tsc -p . or pass --ignoreConfig.
  • Types are erased at runtime. No type annotation validates JSON from an API — parse it with a schema library (Zod, Valibot, ArkType).
  • enum / namespace / parameter properties break Node type stripping. Use as const objects and explicit fields if you run .ts files directly.

One-Liner Summary

TypeScript adds a compile-time type system to JavaScript -- master utility types, generics, discriminated unions, and type guards to catch bugs before they reach production.