Tech Interview RoomStudy guides

TypeScript

Explain mapped types, conditional types and the infer keyword.

Advanced · 2 min read · Lesson 7 of 7 in TypeScript

Mapped types

Build a new object type by iterating over keys: { [K in keyof T]: ... }. Modifiers readonly, ?, -readonly and -? add or remove flags, and the as clause renames or filters keys.

Conditional types

T extends U ? X : Y chooses a type. When T is a bare type parameter and receives a union, the condition is applied to each member (distributive), which is how Exclude works. Wrap in [T] to stop distribution.

infer

Inside the extends clause, infer R captures part of a type into a new variable: the element of an array, a function's return type, a promise's value.

Template literal types

Build string types: `on${Capitalize<K>}` turns 'click' into 'onClick'.

Example

ts
// Make every property a getter function
type Getters<T> = {
  [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};
type UserGetters = Getters<{ name: string; age: number }>;
// { getName: () => string; getAge: () => number }

// Unwrap arrays and promises
type ElementOf<T> = T extends readonly (infer E)[] ? E : never;
type Unpromise<T> = T extends Promise<infer V> ? V : T;
type A = ElementOf<string[]>;          // string
type B = Unpromise<Promise<number>>;   // number

// Keep only the keys whose values are functions
type FunctionKeys<T> = { [K in keyof T]: T[K] extends (...a: any[]) => any ? K : never }[keyof T];
type Keys = FunctionKeys<{ a: number; run(): void; stop(): void }>; // 'run' | 'stop'

Follow-up questions interviewers ask

Try answering each one before you open it.

When is advanced typing too much?

When types become harder to read than the code, slow down the editor, or produce error messages nobody can follow. In application code prefer simple explicit types; keep heavy type-level programming in shared libraries with tests (expectTypeOf in Vitest, or tsd).