ESC

Type to search the knowledge base.

Cheat sheetTypeScript

TypeScript

Types you need in interviews: unions, narrowing, generics, and utility types.

Basics

typescript
let n: number = 1;
const s = 'hi'; // literal type 'hi'
type ID = string | number;

interface User {
  id: ID;
  name: string;
  email?: string; // optional
  readonly createdAt: Date;
}

Narrowing

typescript
function len(x: string | string[]) {
  if (typeof x === 'string') return x.length;
  return x.length; // string[]
}

// Discriminated union
type Result =
  | { ok: true; data: string }
  | { ok: false; error: Error };

function msg(r: Result) {
  if (r.ok) return r.data;
  return r.error.message;
}

Generics

typescript
function first<T>(arr: T[]): T | undefined {
  return arr[0];
}

type ApiResponse<T> = {
  data: T;
  status: number;
};

Utility types

Partial<T>All props optional
Required<T>All props required
Pick<T, K>Subset of keys
Omit<T, K>Without keys
Record<K, V>Key → value map
ReturnType<F>Function return type

unknown vs any

typescript
function parse(json: string): unknown {
  return JSON.parse(json);
}
const data = parse('{}');
// data.foo // error — narrow first
if (typeof data === 'object' && data && 'foo' in data) {
  console.log((data as { foo: unknown }).foo);
}

Interview tips

  • Prefer unknown at boundaries; any is a last resort.
  • Show a discriminated union — strong senior signal.
  • Explain excess property checks on object literals.

Common mistakes

  • !Spamming as any or ! non-null assertions.
  • !enum overuse when union literals suffice.
  • !Confusing interface merging with type aliases.

Related

← All cheat sheets