Record<Keys, Type>
INFO
The Record<Keys, Type>
utility type is available starting from TypeScript 2.1. For more information see in TypeScript Handbook, Release Note.
Overview
Record<Keys, Type>
is a built in utility type in TypeScript that constructs an object type whose property keys are Keys
and whose property values are Type
. This utility can be used to map the properties of a type to another type.
Syntax
ts
type Record<K extends keyof any, T> = { [P in K]: T };
- Keys (K): This is the type of object's keys that the record type generates for us.
- Type (T): This is the type of the object's value generated by the record type.
Record<Keys, Type>;
Examples
Example #1
ts
type CatName = 'miffy' | 'boris' | 'mordred';
interface CatInfo {
age: number;
breed: string;
}
const cats: Record<CatName, CatInfo> = {
miffy: { age: 10, breed: 'Persian' },
boris: { age: 5, breed: 'Maine Coon' },
mordred: { age: 16, breed: 'British Shorthair' },
};
Example #2
ts
function mapObject<K extends string, T, U>(obj: Record<K, T>, f: (x: T) => U): Record<K, U>;
const names = { foo: 'hello', bar: 'world', baz: 'bye' };
const lengths = mapObject(names, s => s.length); // { foo: number, bar: number, baz: number }
Example #3
ts
function groupBy<T, K extends PropertyKey>(items: readonly T[], callbackFn: (item: T) => K): Record<K, T[]> {
const group = {} as Record<K, T[]>;
for (const item of items) {
const key = callbackFn(item);
if (!(key in group)) {
group[key] = [];
}
group[key].push(item);
}
return group;
}
Example #4
ts
type Team = 'frontEnd' | 'backEnd' | 'devops';
interface Employee {
name: string;
age: number;
hobby: string[];
}
const team: Record<Team, Employee[]> = {
frontEnd: [],
backEnd: [],
devops: [],
};
team.frontEnd.push({
name: 'Ky',
age: 30,
hobby: ['hiking', 'football'],
});