Skip to content
Tutorials Center
My learning

Topics

Lesson 41 of 96 ยท Type Manipulation

keyof, typeof and Indexed Access Types

Learn to derive TypeScript types from other types and from values - keyof T, typeof in type positions, indexed access T[K] and T[number], and keyof typeof for constants.

So far you've mostly written types by hand. As programs grow, that leads to duplication: the same list of keys appears in an interface, in a union of allowed field names and in a lookup table, and sooner or later one copy falls out of date. TypeScript's answer is type manipulation: computing new types from existing types, and even from ordinary JavaScript values.

This lesson introduces the three basic operators that every advanced type is built from. keyof T gives the union of a type's property names. typeof value, used in a type position, gives the type of a variable. And indexed access types, T[K] and T[number], look up the type of a property or of an array's elements. Together they let you keep one source of truth and derive everything else from it. The rest of this chapter, from Built-in Utility Types to Conditional Types, builds on them.

Proving types at compile time

When you work with types that only exist at compile time, console.log can't show them. Your editor's hover tooltip can, but a lesson needs proof that runs. This small pair of helper types checks that two types are exactly equal and fails to compile otherwise:

TypeScript The Expect and Equal helpers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

You don't need to understand how Equal works yet (it uses conditional types in a clever way that compares types more strictly than plain assignability). Treat it as a tool: type _x = Expect<Equal<Actual, Expected>>; compiles only if Actual is exactly Expected. If the program prints its message, every check passed. The underscore names are a convention for "unused, exists only to be checked".

keyof: the union of a type's keys

keyof T produces a union of the property names of T, as string literal types (or number and symbol literals for such keys):

TypeScript keyof on object types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

keyof Product includes optional keys like inStock. Notice the second check: a string index signature produces string | number, because JavaScript converts number keys to strings, so scores[0] is the same as scores['0']. Remember that when you write functions that take keyof T for a generic T: the key may be a string, a number or a symbol, and code like `${key}` may need String(key).

Why Object.keys returns string[]

A natural question: if TypeScript knows the keys, why is Object.keys(product) typed string[] rather than (keyof Product)[]? Because of structural typing: an object typed Product may carry extra properties at runtime, so promising only the known keys would be a lie. The failing example below shows the error you hit when you index with such a key, plus two other common mistakes:

TypeScript Common keyof and indexing mistakes (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TEXT
main.ts(10,15): error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'User'.
  No index signature with a parameter of type 'string' was found on type 'User'.
main.ts(13,17): error TS2339: Property 'zip' does not exist on type 'User'.
main.ts(16,23): error TS2538: Type 'field' cannot be used as an index type.
main.ts(16,23): error TS2749: 'field' refers to a value, but is being used as a type here. Did you mean 'typeof field'?

The first error is the Object.keys problem. The second is an indexed access to a property that doesn't exist (more on T[K] below). The last two say that type positions need types: field is a variable, so you must write User[typeof field]. Here's how to loop over an object's keys safely:

TypeScript Iterating over keys safely

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Option 2 is often the best: as const keeps the literal key types and satisfies checks that each entry really is a key of User, so a typo like 'emial' is a compile error. Option 3 is fine for objects you created yourself, as long as you remember it's a promise the compiler can't check.

typeof in type positions

JavaScript's typeof operator returns a string at runtime, such as 'number'. TypeScript reuses the keyword in type positions with a different meaning: typeof x is the static type of the variable x. The context tells you which one you're looking at:

TypeScript Runtime typeof versus type-level typeof

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

typeof in a type position only accepts identifiers and property accesses (typeof defaults.theme is fine). It can't evaluate expressions, so type T = typeof createUser('x') is a syntax error; use ReturnType<typeof createUser> from Built-in Utility Types instead. Deriving Settings from defaults means you never write the shape twice: add a property to the object and the type follows.

Indexed access types: T[K]

An indexed access type looks up the type of a property, using the same bracket syntax as property access in JavaScript. The index must be a type: a string literal, a union of literals, or keyof T:

TypeScript Looking up property types with T[K]

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Order['status'] is especially handy: if someone later adds 'cancelled' to the status union, setStatus accepts it automatically. Note that you must use bracket notation; Order.status is not valid in a type.

In generic code, T[K] with K extends keyof T is the type of "whatever property you asked for", which is how the getProperty helper in Generic Constraints and Defaults gets its precise return type.

T[number]: element types of arrays and tuples

Arrays are indexed by numbers, so T[number] gives the element type of an array type. For a tuple, it gives the union of all its element types, and specific indexes or 'length' work too:

TypeScript Element types with T[number]

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The ROLES pattern is one of the most useful in everyday TypeScript. The array exists at runtime, so you can loop over it, show it in a dropdown or validate input against it with a type guard like isRole. The type Role is derived from it, so the two can never disagree. Without as const, ROLES would be a string[], and Role would be just string. The parentheses in (typeof ROLES)[number] are optional but make the order of operations obvious.

keyof typeof: keys of a constant object

Combine the two operators and you can derive a union of keys from an actual object. This is the idiomatic replacement for many enums:

TypeScript keyof typeof for lookup tables

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Read keyof typeof HTTP_STATUS from right to left: typeof turns the value into its type, then keyof takes that type's keys. (typeof HTTP_STATUS)[StatusName] gives the values. Thanks to as const, those are the exact numbers, not just number. The Record<StatusName, ...> annotation forces the handler table to have exactly one entry per status: leave one out, or add an unknown one, and the code no longer compiles.

The derivation direction is a design choice. Value first (const ROLES = [...] as const, then typeof) is best when you need the list at runtime. Type first (type Role = 'viewer' | 'editor') is enough when the values only appear in type annotations. Either way, write the information once.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is keyof { a: number; b?: string }?

    keyof includes optional properties. The undefined belongs to the property's value type, not to the key.
  2. 2. What is keyof { [key: string]: boolean }?

    A string index signature also accepts number keys, because JavaScript converts them to strings, so keyof gives string | number.
  3. 3. Given const SIZES = ['s', 'm', 'l'] as const;, what is (typeof SIZES)[number]?

    as const makes SIZES a readonly tuple of literals, and indexing it with number gives the union of its element types.
  4. 4. Why is Object.keys(user) typed as string[] rather than an array of keyof User?

    Structural typing allows extra properties, so TypeScript cannot guarantee that every key is one of User's declared keys.
  5. 5. Does type R = typeof makeUser('x'); compile?

    Type-level typeof cannot evaluate expressions such as calls. typeof makeUser gives the function type, and ReturnType extracts its result.

Summary

  • keyof T is the union of T's property names, including optional ones; a string index signature gives string | number.
  • Object.keys() returns string[] because objects may have extra properties; use Object.entries, a typed key list or a deliberate cast.
  • In a type position, typeof x is the static type of a variable or property; it can't evaluate calls, so combine it with ReturnType and Parameters.
  • Indexed access types look up property types: T['key'], T['a' | 'b'], T[keyof T], nested T['a']['b']. The index must be a type.
  • T[number] gives array and tuple element types; (typeof LIST)[number] with as const turns a constant list into a union.
  • keyof typeof OBJ derives key unions from constant objects, so a single value can be the source of truth for its types.

Next: Built-in Utility Types