×

typescript · level 3 · unit 2 · lesson 3

  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

Turn a value into a type with typeof.

You met typeof in Level 1: at runtime it answers with text like "number". Placed where a type belongs, it does something else. That spot is a : after a colon, inside <>, or after type Name =.

In a type position, typeof defaults is a . It asks the checker for the type of the value called defaults. Write the value once and copy its type, so the two can never drift apart. Change the value and the type follows.

const defaults = { volume: 7, theme: "dark", subtitles: false };
type Settings = typeof defaults;
function describe(settings: Settings): string {
  return `Volume ${settings.volume}, ${settings.theme} theme`;
}
console.log(typeof defaults);
console.log(describe({ volume: 3, theme: "light", subtitles: true }));

Line 2 copies a type and line 6 asks a runtime question. Same word, two jobs.