TypeScript Developer interview question · Most asked
What are mapped types? Show how `Partial` or `Readonly` could be implemented.
Summary
Mapped types create new types by iterating over keys: { [K in keyof T]: ... }. Modifiers ?, readonly, -? and -readonly add or remove optionality and readonly-ness, and as clauses remap or filter keys.
Longer Answer
Key remapping with template literal types enables things like generating getter names. Filtering keys uses as with a conditional resolving to never.
Code Example
type MyPartial<T> = { [K in keyof T]?: T[K] };
type Mutable<T> = { -readonly [K in keyof T]: T[K] };
type Getters<T> = {
[K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};
type UserGetters = Getters<{ name: string; age: number }>;
// { getName: () => string; getAge: () => number }
type OnlyStrings<T> = { [K in keyof T as T[K] extends string ? K : never]: T[K] };
Key Points
[K in keyof T]iteration?/readonlymodifiers and-removalasfor key remapping/filtering
More most-asked TypeScript Developer questions
- Explain `any`, `unknown` and `never`.
- What are the differences between `interface` and `type` aliases?
- What is structural typing in TypeScript?
- What is type narrowing and what techniques does TypeScript support?
- What are discriminated unions and why are they powerful?
- What are generics and how do constraints work?
- Which built-in utility types do you use most, and what do they do?
- What is TypeScript and what problems does it solve?