Utility, Mapped and Conditional Types Interview Questions
Name the common utility types and what they do.
| Utility | Does |
|---|---|
Partial / Required / Readonly | make all props optional / required / readonly |
Pick<T, K> / Omit<T, K> | keep / remove some props |
Record<K, V> | object with keys K and values V |
Exclude / Extract / NonNullable | filter union members |
ReturnType / Parameters / Awaited | read types from functions and promises |
Uppercase, Capitalize, ... | transform string literal types |
Implement Pick, Omit and Readonly yourself.
Utility Types From Scratch
Mapped types loop over keys; as filters keys (mapping to never removes them). The type tests compile only if the implementations are right.
type MyPick<T, K extends keyof T> = { [P in K]: T[P] };
type MyOmit<T, K extends PropertyKey> = { [P in keyof T as P extends K ? never : P]: T[P] };
type MyReadonly<T> = { readonly [P in keyof T]: T[P] };
type Equal<X, Y> = (<G>() => G extends X ? 1 : 2) extends (<G>() => G extends Y ? 1 : 2) ? true : false;
type Expect<V extends true> = V;
type User = { id: number; name: string; password: string };
type tests = [
Expect<Equal<MyPick<User, "id" | "name">, Pick<User, "id" | "name">>>,
Expect<Equal<MyOmit<User, "password">, Omit<User, "password">>>,
Expect<Equal<MyReadonly<User>, Readonly<User>>>,
];
console.log("MyPick, MyOmit and MyReadonly match the built-ins");Output
MyPick, MyOmit and MyReadonly match the built-ins
What does infer do? Implement ReturnType and Awaited.
infer X inside a conditional type captures part of a matched type into a new type variable.
type MyReturnType<F> = F extends (...args: any[]) => infer R ? R : never;
type MyAwaited<T> = T extends PromiseLike<infer V> ? MyAwaited<V> : T;
type ElementType<T> = T extends readonly (infer E)[] ? E : never;What is a distributive conditional type?
If the checked type is a naked type parameter, a conditional type is applied to each union member separately: ToArray<string | number> becomes string[] | number[]. Wrap in a tuple ([T] extends [U]) to disable it. Exclude<T, U> = T extends U ? never : T relies on distribution.
What are template literal types? Give a practical use.
String literal types built with backtick syntax: type EventName = `on${Capitalize<Keys>}`. Uses: typed event names, CSS units (`${number}px`), getter names in mapped types, and extracting route params from "/users/:id" with infer (as typed routers do).