What is the Record type in TypeScript?
In TypeScript 2.1, the Record type was introduced, but its functionality isn’t fully clear to me. Here’s an example that uses the Record type:
// For every property K of type T, transform it to U function mapObject<K extends string, T, U>(obj: Record<K, T>, f: (x: T) => U): Record<K, U>
The Advanced Types documentation mentions Record under Mapped Types along with Readonly, Partial, and Pick, providing this basic definition:
type Record<K extends string, T> = { [P in K]: T; }
While Readonly, Partial, and Pick are homomorphic types, Record is not. This might be because Record doesn’t take an input type to copy properties from, making it unique. Here’s an example of a Record type definition:
type Record<K extends string, T> = { [P in K]: T; }
While Readonly, Partial, and Pick are homomorphic types, Record is not. This might be because Record doesn’t take an input type to copy properties from, making it unique. Here’s an example of a Record type definition:
type ThreeStringProps = Record<‘prop1’ | ‘prop2’ | ‘prop3’, string>
This has raised a few questions for me:
Could someone provide a simple definition of what the TypeScript Record type is? Is Record<K, T> essentially a way to specify “all properties on this object will be of type T”? How does the K part factor in here? Does the generic K in Record<K, T> restrict additional keys on the object that aren’t part of K, or does it allow extra keys but only enforce T on the properties in K?
For instance, is the following: type ThreeStringProps = Record<‘prop1’ | ‘prop2’ | ‘prop3’, string>
exactly the same as this?
Copy codetype ThreeStringProps = {prop1: string, prop2: string, prop3: string}