×

typescript · level 3 · unit 3 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Look up a property's type the way you look up its value.

You read a value with rex["age"]. You can read a type the same way. Pet["age"] is an : the type of the age property of Pet, here number. If Pet changes, every lookup follows.

With a generic key it becomes exact. A function that takes key: K can return T[K], so get(rex, "age") gives a number and get(rex, "name") gives a string. For a list, (typeof sizes)[number] means the type of any item in it.

interface Pet {
  name: string;
  age: number;
}
type Age = Pet["age"];
function get<T, K extends keyof T>(item: T, key: K): T[K] {
  return item[key];
}
const rex: Pet = { name: "Rex", age: 4 };
const years: Age = get(rex, "age");
const sizes = ["S", "M", "L"] as const;
const mine: (typeof sizes)[number] = "M";
console.log(years + 1, mine);

Inside an indexed access type, number means any index, so you get every item's type at once.