Interview Q&A / TypeScript
TypeScript interview questions
Types, interfaces, generics and safe patterns for real codebases.
Prefer rapid revision? Practise TypeScript short interview answers →
- What is the never type in TypeScript, and how do you use it for exhaustive checks?
never is the type with no possible values. It is the return type of functions that never finish normally, like one that always throws, and it is what remains after every case of a union has been handled. Assigning the leftover value to never makes the compiler report any case you forgot.
AdvancedIn-depth4 min read - 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