Careeroza
Record
Record of Keys to Values
Record<K, V> is an object type whose keys are K and values are V. With a literal union for K, every key is required, which makes lookup tables complete.
Example
type Category = "electronics" | "books" | "fashion" | "grocery";
const gstRate: Record<Category, number> = {
electronics: 18,
books: 0,
fashion: 12,
grocery: 5,
};
const countByCategory: Record<string, number> = {};
for (const c of ["books", "fashion", "books"]) {
countByCategory[c] = (countByCategory[c] ?? 0) + 1;
}
console.log(gstRate.fashion, gstRate.books);
console.log(countByCategory);Output
12 0
{ books: 2, fashion: 1 }Missing a Key
Example
Leaving out grocery is an error (TS2741).
type Category = "electronics" | "books" | "grocery";
const gstRate: Record<Category, number> = { electronics: 18, books: 0 };Compiler output (tsc)
Line 2: error TS2741: Property 'grocery' is missing in type '{ electronics: number; books: number; }' but required in type 'Record<Category, number>'.