sr✳SHUBHAM RAJFRONTEND ENGINEER
FULL TECHNICAL GUIDEIntermediate3 min read

When should you use Record in TypeScript?

Record describes an object whose keys come from one type and whose values share another type.

TypeScript#types#objects
THE ANSWER / PLAIN ENGLISH

The idea to remember.

Record describes an object whose keys come from one type and whose values share another type. It is useful for dictionaries and fixed configuration maps.

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 when should you use Record 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