Menu

Type Operators: typeof, keyof, and Indexed Access

Lesson 1: Type Operators: typeof, keyof, and Indexed Access

Which operators read types?

Operator Input Produces Example
typeof value A JavaScript value Its TypeScript type typeof config
keyof T A type Union of its property names keyof Product → `'id'
T[K] A type and key The type of that property Product['price'] → number
T[number] An array or tuple type Its element type Product[][number] → Product

Example

@@CODE_BLOCK_0@@

How it works

  • typeof in a type position reads the type of a JavaScript value, so the value stays the single source of truth.
  • Indexed access reaches into nested types without redeclaring them.
  • Combining keyof and T[K] lets functions accept a key and a value that must match.

Common mistakes

Mistake Effect Fix
Confusing JavaScript typeof (runtime) with TypeScript typeof (type position) Wrong code in the wrong place Type positions follow :, type X =, or <>
Redeclaring nested types by hand Duplicates drift apart Use Order['customer']
keyof on a type with an index signature Result is `string number`

Key takeaways

  • typeof, keyof, and T[K] let you derive types instead of repeating them.
  • Keep one source of truth and extract everything else from it.

Try it: From a const ROUTES = { home: '/', cart: '/cart', orders: '/orders' } as const object, derive a RouteName type and a RoutePath type.


TypeScript Tutorial

J

Jebasta





Get in Touch For Details