Interview Q&A / TypeScript
TypeScript interview questions
Types, interfaces, generics and safe patterns for real codebases.
Prefer rapid revision? Practise TypeScript short interview answers →
- How do you rename keys in a mapped type using the as clause?
Add as after the key in a mapped type, like { [K in keyof T as `get${Capitalize<K & string>}`]: () => T[K] }. The expression after as produces the new key name, and mapping a key to never removes it.
AdvancedQuick answer1 min read - What does the infer keyword do in a conditional type?
infer declares a type variable inside the extends clause of a conditional type, letting TypeScript capture part of the matched type. ReturnType is written as T extends (...args: any) => infer R ? R : never.
AdvancedQuick answer1 min read - What is a distributive conditional type?
When a conditional type is applied to a naked type parameter that is a union, it runs once per union member and joins the results. IsString<string | number> becomes IsString<string> | IsString<number>. Wrapping in [T] turns this off.
AdvancedQuick answer1 min read - What is an assertion function in TypeScript?
An assertion function has a return type like asserts x is string. If it returns normally, TypeScript narrows x for the rest of the scope; if the check fails it must throw. It works like a guard that replaces an if block.
AdvancedQuick answer1 min read