Skip to content

keyof & Indexed Types

The Course
•
25 min study

keyof T is the union of property keys known on T. For Book with title:string and pages:number, keyof Book is "title" | "pages". T[K] is an indexed-access type: it describes the value at key K, not an array position.

A generic getter can preserve the relationship: get<T, K extends keyof T>(record: T, key: K): T[K]. Read this left to right: choose a record type, choose one of its keys, and return the type belonging to that key. With key "pages", the result is number; with "title", it is string.

This differs from accepting key:string and returning string|number for every call. A precise relationship gives the caller useful information without an assertion. It still cannot prove unknown external key text belongs to the allowed set; validate that separately.

TypeScript's typeof type query can derive a type from an existing local value, as in type Book = typeof book. That is a compile-time use of typeof, different from the runtime string returned by typeof book. Use named aliases when they make the domain clearer.

Predict, run, and explain

Write down what the program prints before you run it. Use Check types first; the program runs only when the real compiler accepts it.

Predict, then runTypeScript
function get<T, K extends keyof T>(record: T, key: K): T[K] {
  return record[key];
}

const book = { title: "Types", pages: 120 };

console.log(get(book, "title").toUpperCase());
console.log(get(book, "pages").toFixed(0));

Enable JavaScript to edit and type-check this example.

Check your prediction
Text
TYPES
120

Read the compiler error

The generic constraint ties this key to real fields of this record.

Find and fix the type errorTypeScript
function get<T, K extends keyof T>(record: T, key: K): T[K] {
  return record[key];
}

console.log(get({ title: "Types", pages: 120 }, "duration"));

Enable JavaScript to edit and type-check this example.

Check your diagnosis

Use a supported key or deliberately transform the record. No assertion can create the missing property.

Make the selected key determine the result type

A dynamic string and a known property key carry different evidence. K extends keyof T restricts the input key to names present on T; returning T[K] preserves the value type associated with the chosen key. A broad string|number return would throw away that relationship.

This helper does not validate arbitrary key text from a URL or form. The caller must narrow that input before using it as a known key. Also keep type-level indexed access separate from ordinary array indexing, where a position may be absent.

Each key gives its own result typeTypeScript
function get<T, K extends keyof T>(value: T, key: K): T[K] {
  return value[key];
}

const record = { title: "Types", pages: 120 };
const title = get(record, "title");
const pages = get(record, "pages");

console.log(title.toUpperCase());
console.log(pages + 1);

Enable JavaScript to edit and type-check this example.

Check your prediction
Text
TYPES
121

The two calls produce different static result types from the same helper. This lets each caller use type-appropriate operations without a cast.

A key union gives a value unionTypeScript
const record = { title: "Types", pages: 0 };

type Key = keyof typeof record;

function read(key: Key): string | number {
  return record[key];
}

console.log(read("pages"));
console.log(typeof read("title"));

Enable JavaScript to edit and type-check this example.

Check your prediction
Text
0
string

The non-generic read intentionally returns the whole value union because its parameter is the whole key union. Compare that with the per-call relationship in get before choosing an API shape.

Try the rule on new inputs

Call get with every real key, then a misspelled key. Explain why a caller variable typed as string needs additional evidence. Do not assert unknown external text as keyof T without checking it.

Debug a plausible mistake

Exercise

Repair key and result correlation

The title lookup must return a string without a cast, while looking up pages must return a number. Print Read. Preserve the relationship to the specific selected key.

Use Check types to inspect the genuine diagnostic before repairing the code. Keep the intended contract; do not bypass the checker with any, a broad assertion or an ignore comment.

Find and fix the type errorTypeScript
function get<T>(value: T, key: keyof T): T[keyof T] {
  return value[key];
}

const title: string = get({ title: "Read", pages: 100 }, "title");

console.log(title);

Enable JavaScript to edit and type-check this example.

Hint 1: the idea

keyof T names all possible keys, so T[keyof T] combines all their value types.

Hint 2: a first step

Introduce a second type parameter for the actual key, constrained by keyof T.

Show one solution
TypeScript
function get<T, K extends keyof T>(value: T, key: K): T[K] {
  return value[key];
}

const title: string = get({ title: "Read", pages: 100 }, "title");

console.log(title);
Text
Read

With key: keyof T, the return type T[keyof T] is string | number for this record whatever key is passed, so assigning it to title: string failed with TS2322. Adding K captures the literal "title" from the call, and T[K] becomes exactly string. The runtime code is unchanged: only the type of the result was too broad.

Turn key text into a known key

This lesson has said several times not to assert key text with as keyof Book. Here is what to do instead. A sort or filter form sends a column name as a plain string. Passing it straight to get fails with TS2345: Argument of type 'string' is not assignable to parameter of type 'keyof Book', and that error is correct: "author" is a string too.

The evidence comes from a runtime list of the allowed keys and a type predicate that checks membership in it:

Validate key text with a guardTypeScript
type Book = { title: string; pages: number };

const bookKeys: readonly (keyof Book)[] = ["title", "pages"];

function isBookKey(text: string): text is keyof Book {
  return bookKeys.some(key => key === text);
}

function get<T, K extends keyof T>(record: T, key: K): T[K] {
  return record[key];
}

const book: Book = { title: "Types", pages: 120 };

for (const text of ["pages", "author"]) {
  console.log(isBookKey(text) ? get(book, text) : `No column ${text}`);
}

Enable JavaScript to edit and type-check this example.

Check your prediction
Text
120
No column author

The annotation readonly (keyof Book)[] means a misspelled entry such as "titel" in the list is a compile error, and some does the runtime check. Inside the true branch, text has type keyof Book, so get accepts it with no assertion. The list can still leave a key out; that makes the guard stricter, never unsafe. Tomorrow's as const gives another way to derive the key union from such a list.

Your turn

Exercise

keyof & Indexed Types: practice

A filter form for tasks sends a field name as text. A Task has label:string, done:boolean and minutes:number. Write describeField(task, field: string): string returning field=value when field is a real Task key and unknown field: X otherwise. Print label=Review, minutes=25 and unknown field: owner for the three field names. No as anywhere.

Your workspaceTypeScript
// A Task type, a key list, a guard, then describeField.

Enable JavaScript to edit and type-check this example.

Hint 1: the idea

The field arrives as a string, so task[field] is rejected until a runtime check gives the checker evidence that field is a Task key.

Hint 2: a first step

Write a list of the three keys annotated as readonly (keyof Task)[], and a predicate that returns whether some entry equals the text.

Show one solution
One possible solutionTypeScript
type Task = { label: string; done: boolean; minutes: number };

const taskKeys: readonly (keyof Task)[] = ["label", "done", "minutes"];

function isTaskKey(text: string): text is keyof Task {
  return taskKeys.some(key => key === text);
}

function describeField(task: Task, field: string): string {
  if (!isTaskKey(field)) {
    return `unknown field: ${field}`;
  }
  return `${field}=${task[field]}`;
}

const task: Task = { label: "Review", done: false, minutes: 25 };

for (const field of ["label", "minutes", "owner"]) {
  console.log(describeField(task, field));
}

Enable JavaScript to edit and type-check this example.

Text
label=Review
minutes=25
unknown field: owner

After the early return, field has type keyof Task, so task[field] type-checks (as string | boolean | number, which a template literal can format). The checker also verifies every entry in taskKeys is a real key. What it cannot verify is that the guard's body is honest: if isTaskKey returned true for everything, "owner" would compile and print owner=undefined. The "owner" case in the output is the evidence that it doesn't.

Change it and test it

Try calling a string method on get(task,"done") and read the diagnostic. Pass a union key and explain why the result is a union of possible property types. Do not assert arbitrary input text to keyof merely to silence an error.

Was this article helpful?

Your response is saved on this device.