What does Record<K, T>
mean in Typescript?
Typescript 2.1 introduced the Record
type, describing it in an example:
// For every properties 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>
see Typescript 2.1
And the Advanced Types page mentions Record
under the Mapped Types heading alongside Readonly
, Partial
, and Pick
, in what appears to be its definition:
type Record<K extends string, T> = { [P in K]: T; }
Readonly, Partial and Pick are homomorphic whereas Record is not. One clue that Record is not homomorphic is that it doesn’t take an input type to copy properties from:
type ThreeStringProps = Record<'prop1' | 'prop2' | 'prop3', string>
And that's it. Besides the above quotes, there is no other mention of Record
on typescriptlang.org.
Questions
Can someone give a simple definition of what
Record
is?Is
Record<K,T>
merely a way of saying "all properties on this object will have typeT
"? Probably not all properties, sinceK
has some purpose...Does the
K
generic forbid additional keys on the object that are notK
, or does it allow them and just indicate that their properties are not transformed toT
?With the given example:
type ThreeStringProps = Record<'prop1' | 'prop2' | 'prop3', string>
Is it exactly the same as this?:
type ThreeStringProps = {prop1: string, prop2: string, prop3: string}