AI Hints
Home›TypeScript Tutorial›Type Operators
TypeScript · Lesson 61 of 120

typeof Types

Types from values.

⏱ 2 min read▶ Video at 47:39🎓 Free
Watch this lesson in the TypeScript courseWatch on YouTube ↗Full TypeScript course

In a type position, typeof takes a value, and gives you its type. So you can write a value once, and get its type for free.

typeof Types
From the video: typeof Types
  • Write a value
  • Get its type
  • typeof

A type from a config object

Config is a normal object. Typeof config gives its type. A function then requires exactly that shape. Run it.

app.tstypescript
const config = {
  currency: "GBP",
  freeDeliveryFrom: 50,
  stores: ["Leeds", "York"],
};

type Config = typeof config;

function summary(c: Config): string {
  return `${c.stores.length} stores, free delivery from ${c.freeDeliveryFrom} ${c.currency}`;
}

console.log(summary(config));
Output
2 stores, free delivery from 50 GBP

Summary

Typeof in a type gives you the type of a value, so you write it only once. Next, indexed access types.

Key takeaways
  • typeof config
  • One source
  • No duplication
Next up: Indexed Access Types — a property's type