HardConcept

What are mapped types and conditional types in TypeScript?

Technology:
TypeScript
Experience:
Senior

Quick answer

Mapped types build a new object type by looping over keys ({ [K in keyof T]: ... }). Conditional types pick a result with T extends U ? X : Y, which is how many utility types are implemented.

Detailed explanation

Partial<T> is a mapped type that adds ? to every key. You can also remap keys with as ([K in keyof T as ${K & string}Id]). Conditional types power Exclude, Extract and NonNullable. They become interesting with infer, which pulls a piece out of a type (T extends Promise<infer U> ? U : T).

Senior interviews look for judgement: these features belong in shared utility types, not in every component file. If a conditional type is hard to read, a few well-named helpers beat one clever one-liner. Recursion has a depth limit; it is the wrong tool for modelling arbitrarily nested JSON unless you must.

Example

typescript
type ReadonlyFields<T> = { readonly [K in keyof T]: T[K] };
type Awaited<T> = T extends Promise<infer U> ? Awaited<U> : T;
  • TypeScriptMedium

    What is type narrowing in TypeScript?

    Narrowing is when TypeScript shrinks a wide type (such as a union) to a more specific type after a runtime check like typeof, instanceof, in, or a custom type guard.

    Mid-level 路 Senior 路 Types & Type System
  • TypeScriptMedium

    What is the difference between enum and union types in TypeScript?

    A string union such as "admin" | "user" exists only in the type system and erases to plain strings. A TypeScript enum compiles to a JavaScript object (unless it is a const enum), which is extra runtime code and a weaker default.

    Mid-level 路 Senior 路 Types & Type System
  • TypeScriptMedium

    How does TypeScript type inference work?

    TypeScript fills in types you omit: literals get their literal or widened type, function return types are inferred from return statements, and generic arguments are inferred from the values you pass.

    Mid-level 路 Senior 路 Types & Type System
  • TypeScriptEasy

    What is TypeScript and why do we use it?

    TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. It catches type errors in the editor and at build time, and it documents the shape of data for the next person who reads the code.

    Intern 路 Junior 路 Types & Type System