Interview Q&A / TypeScript

INTERVIEW Q&A · 47 QUESTIONS

TypeScript interview questions

Types, interfaces, generics and safe patterns for real codebases.

  1. 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
  2. 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
  3. 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
  4. 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