BTI Beyond The Interviews

Languages · 12 sections

TypeScript

Type system, generics, narrowing, tooling, and the TS interview essentials.

Free · full sheet 126 cards Updated 24 Oct 2026

Types

What are TypeScript's primitive types?

string, number, boolean, null, undefined, symbol, bigint, plus void, never, unknown, any. Arrays: number[] or Array<number>. Tuples: [string, number].

let n: number = 42;
let arr: string[] = ['a','b'];
let tup: [string, number] = ['x', 1];

any vs unknown vs never: what's the difference?

any disables type checking entirely. unknown is the type-safe top type: you must narrow before using. never is the bottom type for values that never occur (throws, infinite loops, empty unions).

let a: any = 1; a.foo();        // no error
let u: unknown = 1;
if (typeof u === 'number') u.toFixed();
function fail(): never { throw new Error('x'); }

What is a union type?

A | B means the value may be any listed member. You must narrow (typeof/instanceof/in/discriminant) before accessing member-specific properties.

type Status = 'loading' | 'success' | 'error';
type Id = string | number;
function len(x: string | string[]) { return Array.isArray(x) ? x.length : x.length; }

What is an intersection type?

A & B requires the value to satisfy both types simultaneously. Commonly used to merge object shapes or add capabilities to existing types.

type User = { id: string; name: string };
type Admin = User & { role: 'admin'; permissions: string[] };
const a: Admin = { id:'1', name:'Ann', role:'admin', permissions:[] };

What are literal types?

A literal type is an exact value such as 'success', 42, or true. Combine literals into unions to model finite states without enums.

type Method = 'GET' | 'POST' | 'PUT' | 'DELETE';
let m: Method = 'GET';
// m = 'PATCH'; // error

What's the difference between void and undefined?

undefined is both a value and a type. void means a function returns nothing meaningful (or its return is ignored); a void-returning function may technically return any value that callers ignore.

function log(msg: string): void { console.log(msg); }
const cb: () => void = () => 42; // allowed: return ignored

How does never enable exhaustiveness checking?

Assign the narrowed value to a never-typed variable in the default branch. If a new union member is added later, the assignment fails to compile, forcing you to handle it.

type Shape = { kind: 'circle'; r: number } | { kind: 'square'; side: number };
function area(s: Shape) {
  switch (s.kind) {
    case 'circle': return Math.PI * s.r ** 2;
    case 'square': return s.side ** 2;
    default: const _exhaustive: never = s; return _exhaustive;
  }
}

What are tuples and readonly tuples?

Tuples are fixed-length arrays with per-position types. Prefix with readonly (or use as const) to prevent mutation and preserve literal element types.

let t: [string, number] = ['a', 1];
const r = ['a', 1] as const; // readonly ['a', 1]
type Pair = readonly [number, number];

What are the pitfalls of enums?

Numeric enums allow reverse mapping and implicit numbering; string enums are safer. const enum is inlined at compile time but is non-erasable syntax: it breaks under isolatedModules and bundlers, and Node's type stripping cannot run it. Many teams prefer a union of string literals.

enum Color { Red, Green = 2, Blue }
// Color[0] === 'Red' (reverse mapping)
const enum Fast { A, B } // inlined; avoid with isolatedModules / erasableSyntaxOnly

How do bigint and symbol types work?

bigint represents arbitrary-precision integers (suffix n). symbol creates unique tokens; unique symbol narrows to a single const value for nominal typing.

const big: bigint = 9007199254740993n;
const sym: unique symbol = Symbol('id');
type WithId = { [sym]: number };

How does strictNullChecks change null/undefined?

With strictNullChecks, null and undefined are not assignable to other types. Optional properties become T | undefined. Use non-null assertions or guards.

let s: string = null; // error with strictNullChecks
function f(x?: string) { return x?.toUpperCase(); }

Interfaces vs Types

interface vs type alias: when to use which?

Use interface for object shapes that may be extended or merged; use type for unions, primitives, tuples, mapped/conditional types, and computed types. Both describe object shapes.

interface User { id: string; name: string }
type Status = 'ok' | 'err';
type Point = [number, number];

What is declaration merging?

Multiple interface declarations with the same name merge into one. Namespaces and modules can merge too. Useful for augmenting third-party types. Type aliases cannot be redeclared.

interface Box { width: number; }
interface Box { height: number; }
const b: Box = { width: 1, height: 2 };

How do extends and intersection differ?

interface extends creates a subtype with conflict checking (incompatible members error). Intersection (&) silently produces never for conflicting properties. Prefer extends for object hierarchies.

interface A { x: string }
interface B extends A { y: number }
// vs
type C = { x: string } & { x: number }; // x: never

What does implements do?

A class implements an interface, promising to provide its members. TS checks structurally; it does not add runtime behavior or inheritance. Interfaces also make good public contracts and plugin points because consumers can augment them via declaration merging, while type aliases cannot be reopened.

interface Serializable { serialize(): string; }
class User implements Serializable {
  serialize() { return JSON.stringify(this); }
}

Can type aliases represent things interfaces cannot?

Yes: primitives, unions, intersections, tuples, mapped types, conditional types, and template literal types. Interfaces can only describe object/callable/constructable shapes.

type ID = string | number;
type Pair<T> = [T, T];
type Keys<T> = keyof T;

How do you augment a third-party module?

Use declare module 'lib' { interface Foo { ... } } to add properties to an existing module's types. Interfaces merge; type aliases do not.

declare module 'express' {
  interface Request { user?: { id: string } }
}

What are index signatures?

Index signatures describe objects with arbitrary keys: { [key: string]: V }. Every named property must also be assignable to V — including undefined when the property is optional. So length?: number requires an index type that accepts undefined; otherwise declare the property as required.

interface Dictionary {
  [key: string]: number;
  length: number;              // known props must be assignable to number
}
const d: Dictionary = { a: 1, b: 2, length: 2 };

interface Sparse {
  [key: string]: number | undefined;
  length?: number;             // OK: undefined is allowed
}

What are call and construct signatures?

Interfaces can describe callable objects ( (x: number): string ) and constructable ones ( new (...args): T ), enabling function types with extra properties.

interface Fn { (x: number): number; label: string; }
const f: Fn = Object.assign((x: number) => x * 2, { label: 'double' });

What is a hybrid type?

A type that is both callable and has properties, e.g. a function with attached metadata, modeled via interface with call signature plus properties.

interface Counter { (start: number): string; interval: number; reset(): void; }

How do readonly properties work in interfaces?

readonly prevents reassignment of the property. It is shallow: nested objects and array contents can still be mutated unless they are made readonly too (DeepReadonly or an immutable library).

interface Config { readonly apiUrl: string; readonly tags: string[]; }
const cfg: Config = { apiUrl: '/api', tags: [] };
// cfg.apiUrl = '/v2';  // error
cfg.tags.push('x');     // allowed: readonly is shallow
type DeepReadonly<T> = { readonly [K in keyof T]: DeepReadonly<T[K]> };

What is an optional property?

Mark with ? : T | undefined. Access returns T | undefined unless narrowed. Use required vs optional to model partial updates.

interface User { id: string; email?: string; }
function greet(u: User) { return u.email?.toUpperCase() ?? 'hi'; }

How do function overloads work?

Declare one or more call signatures, then a single implementation signature. The implementation must be compatible with every overload but is not callable directly. Overloads resolve top-down, so list the most specific signatures first.

function parse(x: string): number;
function parse(x: number): string;
function parse(x: string | number) {
  return typeof x === 'string' ? Number(x) : String(x);
}
parse('42'); // number
parse(42);   // string
// parse(true); // error: no overload matches

Generics

How do you write a generic function?

Declare a type parameter in angle brackets: function identity<T>(x: T): T. TS infers T from arguments; you can also specify it explicitly.

function first<T>(arr: T[]): T | undefined { return arr[0]; }
const n = first([1,2,3]); // number | undefined

How do constraints work?

Use extends to restrict T: <T extends { length: number }>. This lets you access constrained members while keeping the concrete type.

function logLen<T extends { length: number }>(x: T): T {
  console.log(x.length); return x;
}

How do default type parameters work?

Provide a default: <T = string>. Used when inference fails or no argument supplies the type. Defaults can reference earlier params.

function create<T = string>(x?: T): T { return x as T; }
const s = create(); // string

How does type inference work for generics?

TS infers from arguments, return usage, and contextual type. Explicit type args override inference. Failed inference may fall back to the constraint or unknown.

function map<T, U>(xs: T[], f: (x: T) => U): U[] { return xs.map(f); }
const out = map([1,2], x => x.toString()); // string[]

How do generic interfaces and classes work?

Parameterize the whole type: interface Box<T> { value: T }. class Stack<T> { push(x: T): void }. Each instance fixes T.

class Stack<T> {
  private items: T[] = [];
  push(x: T) { this.items.push(x); }
  pop(): T | undefined { return this.items.pop(); }
}

What are keyof and indexed access types?

keyof T yields a union of its keys. T[K] yields the value type for key K. Combine with generics to build type-safe property accessors.

function get<T, K extends keyof T>(obj: T, key: K): T[K] { return obj[key]; }
get({a:1,b:'x'}, 'b'); // string

How do keyof constraints and satisfies work together?

Constrain a type parameter to keyof another type to keep lookups type-safe, and use satisfies to validate a value against a shape without widening away its literal types. Together they type config objects, registries, and theme maps precisely.

type Config = { retries: number; endpoint: string };
const cfg = { retries: 3, endpoint: '/api' } satisfies Config;

function read<K extends keyof Config>(key: K): Config[K] { return cfg[key]; }
read('retries');  // number
read('nope');     // error: not a key of Config

What are mapped types?

Transform each property of a type: { [P in keyof T]: ... }. Add or remove modifiers with +/-readonly and +/-? for optional. Used to build Partial/Required/etc.

type Readonly<T> = { readonly [P in keyof T]: T[P] };
type Optional<T> = { [P in keyof T]?: T[P] };
type Mutable<T> = { -readonly [P in keyof T]: T[P] };
type Required2<T> = { [P in keyof T]-?: T[P] };

What are conditional types?

T extends U ? X : Y selects a type based on assignability. They distribute over unions unless wrapped in brackets: [T] extends [U].

type IsArray<T> = T extends any[] ? true : false;
type R = IsArray<string | number[]>; // boolean (distributes)

type ToArray<T> = T extends any ? T[] : never;
type R2 = ToArray<string | number>; // string[] | number[]

What does infer do?

infer declares a type variable to capture a part of a matched type inside a conditional. Used to unwrap Promises, arrays, function parameters and returns, etc.

type Unwrap<T> = T extends Promise<infer U> ? U : T;
type Flatten<T> = T extends (infer U)[] ? U : T;
type Args<F> = F extends (...a: infer A) => any ? A : never;
type Ret<F> = F extends (...a: any[]) => infer R ? R : never;

What are the built-in utility types?

Partial, Required, Readonly, Pick, Omit, Record, Exclude, Extract, NonNullable, ReturnType, Parameters, ConstructorParameters, InstanceType, Awaited, NoInfer.

type U = Partial<User>;
type P = Pick<User, 'id' | 'name'>;
type O = Omit<User, 'password'>;
type M = Record<string, User>;

What is NoInfer used for?

NoInfer<T> (TS 5.4) marks a parameter position that must not contribute to inference. T is inferred only from the other arguments, so a fallback or default cannot silently widen the inferred type.

function pick<T>(items: T[], fallback: NoInfer<T>): T {
  return items[0] ?? fallback;
}
pick(['a', 'b'], 'c'); // T = string
pick(['a', 'b'], 42);  // error: number not assignable to string

What is variance (in/out) in generics?

TS 4.7+ lets you annotate type params with in (contravariant), out (covariant), or in out (invariant) to control assignability and improve checking speed.

interface Producer<out T> { get(): T; }
interface Consumer<in T> { set(x: T): void; }

How do you write a generic factory?

Accept a constructor type and return instances; use new (...args) => T constraints and InstanceType/ConstructorParameters.

function create<T extends new (...a: any[]) => any>(Ctor: T, ...args: ConstructorParameters<T>): InstanceType<T> {
  return new Ctor(...args);
}

Narrowing

How does typeof narrowing work?

typeof checks narrow unions to specific primitives: 'string', 'number', 'boolean', 'symbol', 'bigint', 'function', 'object', 'undefined'.

function f(x: string | number) {
  if (typeof x === 'string') return x.toUpperCase();
  return x.toFixed(2);
}

How does instanceof narrowing work?

instanceof narrows to a class instance, using the prototype chain. Works for classes and some built-ins; not for interfaces or plain objects.

class Circle { constructor(public r: number) {} }
class Square { constructor(public side: number) {} }
function area(s: Circle | Square) {
  if (s instanceof Circle) return Math.PI * s.r ** 2;
  return s.side ** 2;
}

How does the in operator narrow?

'prop' in obj narrows unions based on whether the property exists. Useful for discriminating object shapes without a tag field.

type A = { a: number } | { b: string };
function f(x: A) {
  if ('a' in x) return x.a + 1;
  return x.b.toUpperCase();
}

What are discriminated unions?

A union where each member shares a common literal property (the discriminant). Switching on it narrows to the matching member.

type Shape =
  | { kind: 'circle'; r: number }
  | { kind: 'square'; side: number };
function area(s: Shape) {
  if (s.kind === 'circle') return Math.PI * s.r ** 2;
  return s.side ** 2;
}

How do you write a custom type guard?

A function returning x is T. TS narrows the variable in the true branch when the guard returns true.

type User = { id: string };
function isUser(x: unknown): x is User {
  return typeof x === 'object' && x !== null && 'id' in x;
}
declare const data: unknown;
if (isUser(data)) data.id;

What are inferred type predicates?

Since TS 5.5, TS infers a type predicate for a function that returns a boolean and performs a narrowing check, so simple guards no longer need an explicit x is T annotation.

function isString(x: unknown) {
  return typeof x === 'string'; // inferred: x is string
}
const vals: unknown[] = ['a', 1];
const strs = vals.filter(isString); // string[]

What are assertion functions?

Functions typed asserts x is T or asserts condition. They throw if the assertion fails and narrow subsequent code on success.

declare const v: unknown;
function assertIsString(x: unknown): asserts x is string {
  if (typeof x !== 'string') throw new Error('not string');
}
assertIsString(v); v.toUpperCase();

How does truthiness narrowing work?

Checking a value in a boolean context narrows out null/undefined/0/''/false/NaN. Be careful: 0 and '' are falsy but valid values, so prefer ?? over || when they are meaningful.

function f(x: string | null) {
  if (x) return x.toUpperCase(); // x: string here
  return 'empty';
}
const count = (input ?? 0) + 1; // 0 is preserved with ??

How does equality narrowing work?

Comparing two variables with ===/!== narrows both when one has a literal or known type, eliminating impossible branches.

function f(x: string | number, y: string | boolean) {
  if (x === y) return x.toUpperCase(); // both string
}

What is control flow analysis?

TS tracks type refinements through if/else, switch, loops, and returns, and re-widens at merge points. Refinements are path-sensitive: a branch that reassigns a variable contributes its new type to the merged result.

let x: string | number = Math.random() > 0.5 ? 'a' : 1;
if (typeof x === 'string') {
  x = 2;                    // still a valid string | number assignment
}
// both paths end with x: number
// (without the reassignment, x would still be string | number here)

let y: string | number = Math.random() > 0.5 ? 'a' : 1;
if (Math.random() > 0.5) y = 42; // the other path keeps y: string
// y: string | number after the merge

How do you narrow arrays and tuples?

Array.isArray narrows unknown to any[]. Check .length or indexed access carefully; TS may not narrow tuples by index without noUncheckedIndexedAccess.

function f(x: unknown) {
  if (Array.isArray(x)) return x.length;
}

What does the non-null assertion operator do?

! asserts a value is non-null/non-undefined at that point. It is a compile-time hint only: it performs no runtime check, so if the value really is null you get a TypeError. Prefer an explicit check when absence is possible.

const el = document.getElementById('app')!; // HTMLElement, not null
el.focus(); // throws at runtime if #app is missing

How do you handle narrowing with branded types?

Branded/nominal types (via a unique symbol intersection) require explicit casts; typeof does not remove the brand, so provide a type guard at the boundary and cast only once inside it.

declare const userIdBrand: unique symbol;
type UserId = string & { readonly [userIdBrand]: 'UserId' };

function isUserId(x: string): x is UserId { return x.startsWith('u_'); }
function load(id: UserId) {}
// load('u_1');              // error: string is not UserId
if (isUserId(raw)) load(raw); // narrowed, no cast needed

Classes

What are public, private, and protected?

public is default and accessible everywhere. private is class-only (TS-enforced, erased at runtime; use # for true runtime privacy). protected is class + subclasses.

class A {
  public x = 1;
  private y = 2;
  protected z = 3;
  #secret = 4; // runtime-private
}

What does readonly do on class members?

readonly allows assignment only in the declaration or constructor. It is compile-time only; the property remains writable in JS unless you use accessors.

class C { readonly id: string; constructor(id: string) { this.id = id; } }

What are parameter properties?

Constructor parameters prefixed with an access modifier become class properties automatically, reducing boilerplate. They are non-erasable syntax, so they are rejected by erasableSyntaxOnly and cannot run under Node's type stripping.

class User {
  constructor(public id: string, private password: string) {}
}

What are abstract classes?

Classes marked abstract cannot be instantiated directly. They can define abstract members that subclasses must implement.

abstract class Animal {
  abstract speak(): string;
  move() { console.log('moving'); }
}
class Dog extends Animal { speak() { return 'woof'; } }

How do static members work?

static members belong to the constructor, not instances. Access via ClassName.member. Static blocks run once on class load.

class Counter { static count = 0; static { Counter.count = 1; } }
Counter.count++;

How do getters and setters work?

get/set accessors control property access; a property with only a getter is readonly. Before TS 5.1 the getter's type had to be assignable to the setter's type (get narrower, set wider). Since TS 5.1 the two may be unrelated types when both are explicitly annotated.

class Celsius {
  #c = 0;
  get value(): number { return this.#c; }        // getter: number
  set value(v: string) { this.#c = Number(v); }  // setter: string
}
// Unrelated get/set types are legal since TS 5.1 (both annotated).
// Before 5.1 this errored: number is not assignable to string.

How does inheritance work?

extends inherits members; super() calls the base constructor. Since TS 4.6, statements may appear before super() as long as they do not reference this; TS still requires super() before any use of this. super.method() calls base methods.

class Animal { constructor(public name: string) {}
  speak() { return this.name; } }
class Dog extends Animal {
  constructor(name: string) {
    const upper = name.toUpperCase(); // OK before super(): does not touch this
    super(upper);
  }
  speak() { return super.speak() + ' woofs'; }
}

What is the override keyword?

override (TS 4.3+) explicitly marks a method as overriding a base member, enabling --noImplicitOverride to catch typos.

class Base { greet() {} }
class Derived extends Base { override greet() { super.greet(); } }

How do you type this in methods?

A fake first parameter (this: Foo) declares the expected this type and is erased at runtime, preventing wrong-context calls. Separately, a this return type gives polymorphic chaining: each subclass returns its own type.

function f(this: Window) { this.alert('hi'); } // explicit this parameter
f.call(window);                                // OK
// f();                                        // error: this context of type void

class Chain { add(x: number): this { return this; } } // polymorphic this return
interface Fluent { clone(): this; }

What are mixins?

Mixins are functions that take a base class and return an extended class, enabling multiple inheritance-like composition.

type Constructor<T = {}> = new (...a: any[]) => T;
function Timestamped<TBase extends Constructor>(Base: TBase) {
  return class extends Base { createdAt = new Date(); };
}

How do abstract property fields work?

Abstract classes can declare abstract properties that subclasses must initialize, useful for template-method patterns.

abstract class Service { abstract readonly name: string; run() { console.log(this.name); } }

What are using and await using?

Explicit resource management (TS 5.2+): using registers a disposable value that is cleaned up at scope exit via Symbol.dispose, even when an error is thrown. await using uses Symbol.asyncDispose and awaits cleanup. Values must implement Disposable/AsyncDisposable; include the esnext.disposable lib (part of ESNext).

class Handle implements Disposable {
  #fd = 1;
  [Symbol.dispose]() { /* close(this.#fd) */ }
}
function work() {
  using h = new Handle(); // disposed when work() exits
}

class Db implements AsyncDisposable {
  async [Symbol.asyncDispose]() { /* close pool */ }
}
async function query() {
  await using db = new Db(); // cleanup is awaited on exit
}

Modules & Namespaces

How do ES modules work in TS?

import/export statements define modules. Each file with top-level import/export is a module; otherwise it's a global script.

export function add(a: number, b: number) { return a + b; }
import { add } from './math';

Default vs named exports?

Named exports allow multiple exports and tree-shaking. Default exports are convenient for single primary export but harder to refactor/rename.

export default class Foo {}
export const bar = 1;
import Foo, { bar } from './m';

What are namespaces?

Namespaces (internal modules) group related code under a name. Largely superseded by ES modules; still used for declaration files and global augmentation. Namespaces that emit runtime code are non-erasable syntax, so prefer declare namespace for types.

namespace Utils { export function clamp(n: number, lo: number, hi: number) { return Math.max(lo, Math.min(hi, n)); } }
Utils.clamp(5, 0, 10);

How does module resolution work?

moduleResolution determines how import paths resolve. For Node use node16 or nodenext (with a matching module setting); for a bundler use bundler. The legacy node (node10) and classic values were deprecated in TS 6.0 and removed in TS 7. baseUrl is also deprecated: paths entries resolve relative to the tsconfig file without it.

// tsconfig.json
{
  "compilerOptions": {
    "module": "nodenext",
    "moduleResolution": "nodenext",
    "paths": { "@/*": ["./src/*"] }
  }
}

What are declaration files (.d.ts)?

Files containing only type declarations, no runtime code. Used to type JS libraries. Ambient declarations describe existing runtime values.

declare function fetch(input: string): Promise<Response>;
declare const VERSION: string;
declare module 'untyped-lib';

What are ambient declarations?

declare keyword tells TS a value/type exists at runtime but is defined elsewhere (global, JS file, or another module).

declare global { interface Window { analytics: Analytics; } }
export {};

How do dynamic imports type?

import('module') returns a Promise of the module namespace. Use for code splitting and conditional loading; types are inferred.

async function load() {
  const { default: Foo } = await import('./Foo');
  return new Foo();
}

What are re-exports?

export { x } from './m' or export * from './m' re-expose members, useful for barrel files. Beware of circular re-exports.

// index.ts
export * from './a';
export { default as B } from './b';

What is isolatedModules?

Requires each file to be transpilable independently (no cross-file type-only re-exports without 'type'). Needed for Babel/swc/esbuild and Node's type stripping. Prefer verbatimModuleSyntax (TS 5.0+), which enforces explicit import type / export type at the syntax level. Pair it with erasableSyntaxOnly (TS 5.8) to reject enums, runtime namespaces, and parameter properties when Node strips types.

// verbatimModuleSyntax: true
import type { Foo } from './foo';
export type { Foo };
export { bar } from './foo';
// a value import used only as a type is an error: make it explicit

How does CommonJS interop work?

esModuleInterop enables default imports from CommonJS modules (import fs from 'fs'). allowSyntheticDefaultImports only affects types.

import fs from 'node:fs'; // with esModuleInterop
import * as fs2 from 'node:fs';

What are side-effect imports?

import './polyfill' runs a module for its side effects without binding names. Used for global setup and CSS.

import './register-components';
import 'reflect-metadata';

What are project references?

Composite projects split a codebase into buildable units with incremental builds and dependency ordering via references in tsconfig.

// tsconfig.json: { "references": [{ "path": "./packages/core" }] }

Advanced Types

What are template literal types?

Type-level string manipulation: `on${Capitalize<Event>}`. Enables typed event names, route params, and CSS property names.

type Event = 'click' | 'focus';
type Handler = `on${Capitalize<Event>}`; // 'onClick' | 'onFocus'

What are recursive types?

Types that reference themselves, used for JSON, trees, and nested structures. TS has depth limits; use carefully.

type Json = string | number | boolean | null | Json[] | { [k: string]: Json };

What is key remapping (as clause)?

Mapped types can rename keys with `as`: { [K in keyof T as NewKey]: T[K] }. Filter by mapping to never.

type Getters<T> = { [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K] };
type OmitByType<T, U> = { [K in keyof T as T[K] extends U ? never : K]: T[K] };

What are branded/nominal types?

Intersect a primitive with a phantom property keyed by a unique symbol to prevent accidental mixing of same-shaped values like UserId vs OrderId. The brand exists only in the type system.

declare const brand: unique symbol;
type Brand<T, B> = T & { readonly [brand]: B };

type UserId = Brand<string, 'UserId'>;
type OrderId = Brand<string, 'OrderId'>;
// const id: UserId = 'u_1'; // error: plain string is not branded

What is the satisfies operator?

satisfies (TS 4.9) checks that a value matches a type without widening it to that type, preserving literal inference and catching typos. Combine with as const when you also want tuples and readonly literals.

const palette = {
  red: [255, 0, 0],
  green: '#00ff00',
} as const satisfies Record<string, string | readonly number[]>;
// palette.red is readonly [255, 0, 0], checked against the shape

What are const type parameters?

TS 5.0: <const T> infers literal/readonly types from arguments, avoiding as const at call sites.

function of<const T>(x: T): T { return x; }
const v = of({ a: 1 }); // { readonly a: 1 }

What are variadic tuple types?

Spread elements in tuples: [...T, ...U] concatenates. Enables typed append/prepend and function composition.

type Concat<A extends any[], B extends any[]> = [...A, ...B];
type R = Concat<[1,2], [3]>; // [1,2,3]

What are higher-kinded-ish type functions?

TS has no higher-kinded types, but you can simulate with generic interfaces and conditional types to map over type constructors.

type Apply<F, X> = F extends (x: X) => infer R ? R : never;

How do you limit recursion depth?

Recursive types can hit 'Type instantiation is excessively deep' errors. TS allows roughly 50 levels of instantiation depth for ordinary recursion, and up to ~1000 for conditional types written tail-recursively (TS 4.5+). Pass a depth counter tuple so recursion stops before the limit.

type Prev = [never, 0, 1, 2, 3, 4, 5];

type DeepPartial<T, D extends number = 5> =
  D extends 0 ? T : { [K in keyof T]?: DeepPartial<T[K], Prev[D]> };

type Cfg = DeepPartial<{ a: { b: { c: string } } }>; // stops after 5 levels

Decorators

What are decorators in TypeScript?

Special declarations (prefixed @) attached to classes, methods, accessors, properties, or parameters. TS has legacy (experimental) and new (stage 3, TS 5.0) decorators.

@sealed
class Foo { @log method() {} }

How do legacy decorators differ from new ones?

Legacy decorators (experimentalDecorators) receive (target, key, descriptor) and can mutate. New stage-3 decorators receive (value, context) and are more standardized; they cannot change parameter types.

// tsconfig: "experimentalDecorators": true for legacy

What is a class decorator?

Receives the class (legacy) or constructor (new) and can replace or annotate it. Used for sealing, registration, or metadata.

function sealed<T extends Function>(ctor: T) {
  Object.seal(ctor); Object.seal(ctor.prototype);
  return ctor;
}

What is a method decorator?

Wraps or replaces a method. Legacy form gets the descriptor; new form gets the method and context.addInitializer.

function log(target: any, key: string, desc: PropertyDescriptor) {
  const orig = desc.value;
  desc.value = function (...a: any[]) { console.log(key, a); return orig.apply(this, a); };
}

What is a property decorator?

Legacy property decorators receive (target, propertyKey) but no descriptor; they often register metadata. New decorators receive (undefined, context).

function readonly(target: any, key: string) {
  // register metadata; actual readonly via accessor
}

What is an accessor decorator?

Decorates get/set accessors. New decorators can replace the accessor; legacy gets the descriptor.

function enumerable(value: boolean) {
  return function (_t: any, _k: string, desc: PropertyDescriptor) { desc.enumerable = value; };
}

What is a parameter decorator?

Legacy-only: receives (target, method, paramIndex). Used to record metadata (e.g., DI). Not in stage-3 decorators.

function inject(target: any, key: string, idx: number) { /* record */ }

What are decorator factories?

Functions that return the actual decorator, allowing parameters: @log('info') instead of @log.

function log(level: string) {
  return function (target: any, key: string) { /* use level */ };
}

What is decorator composition order?

Multiple decorators apply bottom-up for the decorator functions but top-down for factory evaluation: factories run top-down, decorators run bottom-up.

@f() @g() method() {} // f factory, then g factory; g decorator, then f decorator

What is emitDecoratorMetadata?

With experimentalDecorators, emits design:type/design:paramtypes/design:returntype metadata for reflection. Requires reflect-metadata polyfill.

// tsconfig: "emitDecoratorMetadata": true
import 'reflect-metadata';

What are common decorator use cases?

Frameworks like NestJS/Angular use decorators for DI, routing, validation, and ORM mapping. They reduce boilerplate but add magic.

@Controller('users')
class UserController { @Get(':id') findOne(@Param('id') id: string) {} }

How do you enable new decorators?

Use a TS 5.0+ compiler without experimentalDecorators. New decorators are standard stage-3 ECMAScript, but no JS runtime ships them natively yet: TS downlevels them to helper calls. target: ES2022 is not required; any supported target works.

// tsconfig.json
{ "compilerOptions": { "experimentalDecorators": false } }
// TS emits decorator helpers; the target stays your normal choice

Config & Tooling

What is tsconfig.json?

The TypeScript configuration file controlling compiler options, file inclusion, and project structure. Extends base configs via 'extends'. @tsconfig/node22 (or node24) matches current LTS releases; @tsconfig/node20 targets Node 20, which reached end-of-life in April 2026.

{
  "extends": "@tsconfig/node22/tsconfig.json",
  "compilerOptions": { "outDir": "dist" },
  "include": ["src"]
}

What does strict: true enable?

Enables strictNullChecks, noImplicitAny, strictFunctionTypes, strictBindCallApply, strictPropertyInitialization, noImplicitThis, alwaysStrict, useUnknownInCatchVariables, and strictBuiltinIteratorReturn (TS 5.6). It does not include noUncheckedIndexedAccess or exactOptionalPropertyTypes.

{ "compilerOptions": { "strict": true } }

What are target and lib?

target sets the emitted JS version (ES2022+ is a good default). lib declares available type definitions (DOM, ES2022). Use lib to include DOM types in Node projects carefully.

{ "compilerOptions": { "target": "ES2022", "lib": ["ES2022"] } }

What are module and moduleResolution?

module sets the output module format (ESNext/CommonJS/NodeNext). moduleResolution sets how imports resolve. For Node use node16 or nodenext with a matching module; for bundlers use bundler. The legacy node (node10) and classic values were removed in TS 7.

{ "compilerOptions": { "module": "nodenext", "moduleResolution": "nodenext" } }

What is noEmit?

Type-check only; do not write output files. Used when a bundler (Vite/esbuild) handles emission.

{ "compilerOptions": { "noEmit": true } }

What are declaration and emitDeclarationOnly?

declaration emits .d.ts files. emitDeclarationOnly emits only declarations (no JS), useful when bundler emits JS but you need types.

{ "compilerOptions": { "declaration": true, "emitDeclarationOnly": true, "outDir": "types" } }

What is isolatedDeclarations?

TS 5.5: requires explicit types on exported declarations whose types cannot be inferred syntactically, so .d.ts files can be emitted without a full type check. It enables fast, parallel declaration emit in monorepos and bundler pipelines; it has no runtime effect.

function makeConfig() { return { retries: 3 }; }

export const VERSION: string = '1.0';                     // OK: explicit
export function add(a: number, b: number): number { return a + b; } // OK
export const cfg = makeConfig(); // error TS9010: add an explicit type

How do include/exclude/files work?

include/exclude are glob patterns; files lists explicit files. exclude defaults to node_modules. Use references for multi-project setups.

{ "include": ["src/**/*"], "exclude": ["**/*.test.ts"] }

What is noUncheckedIndexedAccess?

When enabled, accessing an array/tuple element returns T | undefined unless you've checked. Catches out-of-bounds assumptions at compile time.

{ "compilerOptions": { "noUncheckedIndexedAccess": true } }
const a = [1,2,3];
const x = a[10]; // number | undefined

What is exactOptionalPropertyTypes?

It distinguishes a missing property from a present-but-undefined one. With it on, x?: number does not accept an explicit undefined unless the type says so. Optional properties then model absence precisely, which matters when serializing or forwarding objects.

// exactOptionalPropertyTypes: true
interface A { x?: number }
const a1: A = {};                 // OK: x is absent
const a2: A = { x: undefined };   // error: undefined is not number

interface B { x?: number | undefined }
const b1: B = { x: undefined };   // OK: explicitly allowed

What is incremental compilation?

incremental saves build info to .tsbuildinfo for faster rebuilds. composite implies incremental.

{ "compilerOptions": { "incremental": true, "tsBuildInfoFile": ".tsbuildinfo" } }

How do ESLint and Prettier integrate?

ESLint 9+ uses flat config (eslint.config.js) instead of the legacy .eslintrc. Use the typescript-eslint package, whose tseslint.config(...) helper composes the parser, plugin, and recommended rules. eslint-config-prettier turns off formatting rules; run tsc --noEmit for types and Prettier for formatting.

// eslint.config.js
import tseslint from 'typescript-eslint';

export default tseslint.config(
  ...tseslint.configs.recommended,
  { rules: { '@typescript-eslint/no-explicit-any': 'warn' } }
);

tsc vs bundlers: which to use?

tsc provides type checking and .d.ts emit. Bundlers (Vite/esbuild/swc) are faster for transpilation but skip type checking; run tsc --noEmit in CI.

npm run typecheck  # tsc --noEmit
npm run build      # vite build

What are declaration maps?

declarationMap generates .d.ts.map so 'Go to Definition' jumps to original .ts source instead of .d.ts.

{ "compilerOptions": { "declaration": true, "declarationMap": true } }

How does Node run TypeScript natively?

Node 22.6+ can execute .ts files by stripping types (on by default from Node 23.6 and stable in Node 24). Stripping is per-file and cannot transform non-erasable syntax: enums, namespaces with runtime code, parameter properties, and import =. Set erasableSyntaxOnly (TS 5.8) so tsc rejects those constructs, and verbatimModuleSyntax so type-only imports are explicit. Node does not read tsconfig.json at runtime; use --experimental-transform-types if you truly need enums or namespaces.

node --experimental-strip-types src/main.ts   # Node 22.6+; default later
// tsconfig.json
{
  "compilerOptions": {
    "erasableSyntaxOnly": true,
    "verbatimModuleSyntax": true,
    "noEmit": true
  }
}

What is the TS 7 native compiler (tsgo)?

TypeScript 7 is the native Go rewrite of the compiler: the tsc in typescript@7 is a native binary with much faster type checking and the same type semantics. During the preview it shipped as @typescript/native-preview with a tsgo binary, so that name still appears in docs and CI. Legacy options such as moduleResolution node10/classic are removed, so audit tsconfig and compiler-API-based plugins before upgrading.

npm i -D typescript@7
npx tsc --noEmit -p tsconfig.json   # native compiler
# preview name: npx tsgo --noEmit -p tsconfig.json

Common Gotchas

Type assertion vs type cast?

'as T' is a compile-time assertion with no runtime conversion; it can lie. Casting through unknown (a double assertion) bypasses assignability checks entirely. Validate external data at runtime with a schema library instead of asserting it.

const x = value as User;             // no runtime check
const y = value as unknown as User;  // double assertion: bypasses assignability
// const u = UserSchema.parse(value); // runtime-checked alternative

What is structural typing?

TS compares types by shape, not name. Two types with same members are interchangeable, which can cause accidental compatibility.

interface A { x: number }
interface B { x: number }
const a: A = { x: 1 };
const b: B = a; // OK

What is covariance/contravariance in functions?

Function parameters are checked contravariantly under strictFunctionTypes and returns covariantly. Method parameters remain bivariant, an intentional unsoundness that keeps common patterns (like Array methods) assignable; function-typed properties do not get that escape hatch.

class Animal { name = '' }
class Dog extends Animal { bark() {} }

declare const f: (x: Animal) => Dog;
const g: (x: Dog) => Animal = f; // OK: wider parameter, narrower return

const bad: (x: Animal) => Dog = (x: Dog) => new Dog(); // error: parameter too narrow

interface M { fn(x: Animal): void }        // method: bivariant
interface P { fn: (x: Animal) => void }   // property: contravariant
declare const m: M;
const p: P = m;                            // OK because methods are bivariant

What are excess property checks?

Object literals assigned to a typed variable are checked for extra properties. Spreading or intermediate variables bypass the check.

interface U { name: string }
const u: U = { name: 'a', age: 1 }; // error
const o = { name: 'a', age: 1 }; const u2: U = o; // OK

What is type widening?

let bindings widen literals to base types (string), while const preserves literals. Use as const to prevent widening.

let x = 'hi'; // string
const y = 'hi'; // 'hi'
const z = { a: 1 } as const; // { readonly a: 1 }

What is contextual typing?

TS infers parameter types from the expected function type, so you often omit annotations in callbacks.

const nums = [1,2,3];
nums.map(x => x.toFixed()); // x inferred as number

Optional property vs | undefined?

Optional (?) means the property may be absent. Explicit | undefined means present but possibly undefined. Affects destructuring and excess checks; under exactOptionalPropertyTypes, ? alone even rejects an explicit undefined.

interface A { x?: number; }
interface B { x: number | undefined; }
const a: A = {};        // OK
const b: B = {};        // error: x required

How do you validate data at runtime (zod/valibot)?

Types are erased at runtime, so data from APIs, JSON, env vars, and forms must be parsed. Schema libraries validate the value and infer its static type from the same definition, keeping the check and the type in sync. Zod is the most common choice; Valibot is a lighter, tree-shakeable alternative with the same idea (v.object, v.parse, v.InferOutput).

import { z } from 'zod';

const User = z.object({
  id: z.string(),
  email: z.string().email(),
});
type User = z.infer<typeof User>;

const user = User.parse(await res.json()); // throws if the shape is wrong

TypeScript with React

How do you type a React component and its props?

Declare a props type and annotate the destructured parameter. React.ReactNode covers anything renderable; React.ComponentPropsWithoutRef<'button'> reuses the DOM props so you do not re-declare onClick, disabled, etc. React.FC is optional — it no longer adds implicit children, and a plain function usually gives clearer errors.

type CardProps = {
  title: string;
  children?: React.ReactNode;
};

export function Card({ title, children }: CardProps) {
  return <section><h2>{title}</h2>{children}</section>;
}

type ButtonProps = React.ComponentPropsWithoutRef<'button'> & {
  variant?: 'primary' | 'ghost';
};
export function Button({ variant = 'primary', ...rest }: ButtonProps) {
  return <button data-variant={variant} {...rest} />;
}

How do you type React hooks?

Annotate useState when the initial value is null or a union, useRef with the element type (and null), and type event handlers with React.ChangeEvent/FormEvent. Generic parameters keep the state and setters precise.

const [count, setCount] = useState<number>(0);
const [user, setUser] = useState<User | null>(null);
const inputRef = useRef<HTMLInputElement>(null);

function onChange(e: React.ChangeEvent<HTMLInputElement>) {
  setUser({ id: e.target.value });
}
useEffect(() => { inputRef.current?.focus(); }, []);
// type a reducer's actions as a discriminated union and pass it to useReducer

How do you write a generic React component?

Make the props type generic; TS infers T from the props at the JSX call site. In .tsx arrow functions, write <T,> or <T extends unknown> so the parser does not treat <T> as JSX.

type ListProps<T> = {
  items: T[];
  getKey: (item: T) => string;
  render: (item: T) => React.ReactNode;
};

function List<T>({ items, getKey, render }: ListProps<T>) {
  return <ul>{items.map(i => <li key={getKey(i)}>{render(i)}</li>)}</ul>;
}

<List
  items={[{ id: '1', name: 'Ada' }]}
  getKey={u => u.id}
  render={u => u.name}
/>;

What's new in TypeScript 5.x

satisfies operator (4.9+) vs a type annotation?

const c = {...} satisfies Config checks against the type but keeps the narrower inferred type (literal keys/values). An annotation widens the type to Config.

const c = { port: 8080, host: "localhost" } satisfies Config;
// c.port is number literal 8080, still checked against Config

const d: Config = { port: 8080, host: "localhost" };
// d.port is number (widened)

using declarations (TS 5.2)?

Explicit resource management: using f = open() calls [Symbol.dispose]() automatically at the end of the scope (await using for async). Like try-with-resources.

{
  using f = open("file.txt");        // calls f[Symbol.dispose]() on scope exit
  await using db = await connect();   // AsyncDisposable
}   // disposed here, even on throw

Other TS 5.x features worth naming?

Standard ECMAScript decorators (5.0), const type parameters (5.0), NoInfer<T> (5.4), inferred type predicates from filter (5.5), --erasableSyntaxOnly for Node's native type stripping (5.8). Also: the Go-based native compiler (TS 7 / "tsgo") promises ~10× faster builds.

function f<const T extends readonly string[]>(x: T) { }  // const type param
function g(x: NoInfer<string>) { }                        // 5.4
arr.filter((x): x is Foo => !!x);                         // 5.5 inferred predicate
// tsc --erasableSyntaxOnly   (5.8, Node type stripping)
// tsgo                      (TS 7 native compiler, ~10x faster)

unknown vs any vs never?

any turns off checking. unknown is a safe top type: you must narrow before use. never is the empty type (unreachable code; exhaustive-switch checks: const _x: never = v).

let a: any;      a.foo.bar;        // unchecked, no error
let u: unknown;  u.foo;            // error: narrow first

switch (s) { case 'a': ...; default: const _x: never = s; }  // exhaustiveness

Want this as flashcards? Study these 126 cards recall-first in the browser — flip, answer out loud, grade yourself.

Open the card deck