TSTypeScript
AdvancedLesson 12 of 15

keyof, typeof & Mapped Types – TypeScript

Computing types from values and from other types.

keyof T returns the keys of a type as a union, typeof value the type of a value, and indexed access T[K] the type of a property:

const konfig = { host: "localhost", port: 8080, debug: false };

type Konfig = typeof konfig;                   // { host: string; port: number; debug: boolean }
type Schluessel = keyof Konfig;                // "host" | "port" | "debug"
type PortTyp = Konfig["port"];                 // number
type Werte = Konfig[keyof Konfig];             // string | number | boolean

function lese<K extends keyof Konfig>(key: K): Konfig[K] {
  return konfig[key];
}
console.log(lese("port") + 1);                 // number

Mapped types build a new type by looping over all keys of another one. This is how Partial, Readonly and co. come about – you can build your own:

type Optional<T> = { [K in keyof T]?: T[K] };           // like Partial
type Schreibbar<T> = { -readonly [K in keyof T]: T[K] };  // remove readonly
type Pflicht<T> = { [K in keyof T]-?: T[K] };             // remove ?
type Boolesch<T> = { [K in keyof T]: boolean };

interface Person { name: string; alter: number }
type Pruefung = Boolesch<Person>;              // { name: boolean; alter: boolean }
const pflicht: Pruefung = { name: true, alter: false };

With as in the key clause (key remapping) you rename keys or filter them – e.g. getter names from property names:

type Getter<T> = {
  [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};
type PersonGetter = Getter<Person>;
// { getName: () => string; getAlter: () => number }

const g: PersonGetter = { getName: () => "Ada", getAlter: () => 36 };
console.log(g.getName(), g.getAlter());

type NurZahlen<T> = {
  [K in keyof T as T[K] extends number ? K : never]: T[K];
};
type Zahlen = NurZahlen<Person>;               // { alter: number }
TipThink in "type functions": type aliases with parameters are functions at the type level. Keep them small and name them well – types that are too clever are hard to read and produce incomprehensible error messages.