Lesson 11 of 11 · 15 min

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

  1. Define type Getters<T>: for each property name of T, a method getName(): T["name"].
  2. Implement makeGetters<T extends object>(obj: T): Getters<T>. (Inside, build the object with a loop and use as Getters<T> for the return; TypeScript cannot follow the key renaming at runtime.)
  3. Define type Unwrap<T> = T extends (infer E)[] ? E : T and implement unwrap<T>(value: T): Unwrap<T>.

The typed lines at the bottom of the starter must compile.

main.ts
// type Getters<T> = ...

function makeGetters<T extends object>(obj: T): Getters<T> {
  return {} as Getters<T>;
}

// type Unwrap<T> = ...

function unwrap<T>(value: T): Unwrap<T> {
  return value as Unwrap<T>;
}

const g = makeGetters({ name: "Ana", age: 30 });
const n: string = g.getName();
const a: number = g.getAge();
const first: number = unwrap([5, 6]);
console.log(n, a, first);

TypeScript 5.9 runs right here in your browser. The first run downloads about 1.5 MB; after that it is instant.

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…