sr✳SHUBHAM RAJFRONTEND ENGINEER
FULL TECHNICAL GUIDEIntermediate3 min read

What does keyof do in TypeScript?

keyof produces a union of property keys for a type.

TypeScript#types#generics
THE ANSWER / PLAIN ENGLISH

The idea to remember.

keyof produces a union of property keys for a type. Combine it with a generic constraint to build safe helpers that read existing object fields.

From first example to real project.

Start with the smallest working idea, examine a more detailed example, then look at a real application pattern. Adapt dependencies, error handling and data models to your project.

Basic: a generic function

01 / BEGINNER

Keep the relationship between the input and output type.

TYPESCRIPT / EXAMPLE
function first<T>(items: T[]): T | undefined {
  return items[0];
}
const name = first(['Ada', 'Lin']); // string | undefined

Intermediate: constrain a generic

02 / INTERMEDIATE

Require a stable ID while preserving other fields.

TYPESCRIPT / EXAMPLE
function byId<T extends { id: string }>(items: T[]): Map<string, T> {
  return new Map(items.map(item => [item.id, item]));
}

Real scenario: typed API response

03 / REAL SCENARIO

Validate runtime data; a generic type alone cannot validate JSON.

TYPESCRIPT / EXAMPLE
async function fetchJson<T>(url: string, guard: (x: unknown) => x is T): Promise<T> {
  const response = await fetch(url);
  if (!response.ok) throw new Error('Request failed');
  const value: unknown = await response.json();
  if (!guard(value)) throw new Error('Unexpected API payload');
  return value;
}

Try it in your own words.

Explain what does keyof do in TypeScript without looking at the code. Then modify the intermediate example, describe one trade-off and identify when the real-world pattern fits.

Keep learning here.

Explore more in-depth guides, exercises and related interview questions in this library.

Browse TypeScript study guides ↗
← Back to question library

Have something
in mind?

Start a conversation