typestar

keyof and indexed access in TypeScript

The two operators every generic helper is built from.

interface Run {
  lang: string;
  tpm: number;
  stars: 1 | 2 | 3;
}

type RunKey = keyof Run;
type RunValue = Run[keyof Run];
type Stars = Run["stars"];

function get<T, K extends keyof T>(source: T, key: K): T[K] {
  return source[key];
}

function pluck<T, K extends keyof T>(rows: T[], key: K): T[K][] {
  return rows.map((row) => row[key]);
}

const run: Run = { lang: "ts", tpm: 98, stars: 3 };
const key: RunKey = "tpm";
const value: RunValue = get(run, key);
console.log(value, pluck([run, run], "lang"));

How it works

  1. keyof T is the union of T's keys.
  2. T[K] is the type of that property.
  3. T[keyof T] is the union of all the value types.

Keywords and builtins used here

The run, in numbers

Lines
22
Characters to type
503
Tokens
176
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 106 seconds.

Type this snippet

Step 1 of 4 in Reading types, step 5 of 20 in Generics.

← Previous Next →