keyof, mapped and conditional types
keyof and indexed access
keyof T is the union of a type's property names, and T[K] is the type of property K:
interface Car { make: string; year: number }
type CarKey = keyof Car; // "make" | "year"
type Year = Car["year"]; // number
Mapped types
A mapped type builds a new object type by looping over keys. This is how Partial and Readonly are written:
type MyPartial<T> = { [K in keyof T]?: T[K] };
type Flags<T> = { [K in keyof T]: boolean };
With as you can rename keys, using template literal types to build new names:
type Setters<T> = {
[K in keyof T as `set${Capitalize<string & K>}`]: (value: T[K]) => void;
};
type CarSetters = Setters<Car>;
// { setMake: (value: string) => void; setYear: (value: number) => void }
(string & K keeps only string keys, since Capitalize works on strings.)
Conditional types
A conditional type chooses a type based on another, like a ternary for types. infer captures part of a type:
type IsString<T> = T extends string ? "yes" : "no";
type ElementOf<T> = T extends (infer E)[] ? E : T;
type A = ElementOf<number[]>; // number
type B = ElementOf<string>; // string
These features let libraries describe APIs precisely, so every call is checked without anyone writing types by hand.
Your task
- Define
type Getters<T>: for each propertynameofT, a methodgetName(): T["name"]. - Implement
makeGetters<T extends object>(obj: T): Getters<T>. (Inside, build the object with a loop and useas Getters<T>for the return; TypeScript cannot follow the key renaming at runtime.) - Define
type Unwrap<T> = T extends (infer E)[] ? E : Tand implementunwrap<T>(value: T): Unwrap<T>.
The typed lines at the bottom of the starter must compile.