#Why and when would I want to use a Record over a typed object/map?

7 messages · Page 1 of 1 (latest)

sturdy igloo
#

i assume you're talking about index signatures specifically (Record can be used to create types without index signatures too)

IMO it's generally better to use a Map if you want a key/value store, but some libraries (especially older ones from before Map was a thing) use plain objects for this instead, so TypeScript needs a way to model them

somber mirage
#

@icy garden Yeah, Record is just a convenience utility for describing plain object types.

#

If the general question is "when to use plain objects and when to use Maps", well it depends.

#

I tend to use plain objects most of the time: they're what I get from REST APIs, they're easier to work with in a non-mutable way (which is important for React, for example), you can model composite structures like:

type Foo = Record<"a" | "b" | "c", string> & 
   Record<"x" | "y" | "z", number>
unique dawn
#

Its easier to use records when the key is not just a string. You can have a record where the key is an object. Its just more flexible when working with maps which might be keyed off the object itself. Feels anti pattern but buyer beware etc etc

sturdy igloo
#
type X = Record<'Dog' | 'Bat' | 'Cat', string>

is exactly the same as

type X = { Dog: string, Bat: string, Cat: string }
type Y = Record<string, string>

is exactly the same as

type Y = { [key: string]: string }

Record itself is defined as a simple mapped type, and mapped types that map over an infinitely-sized key type (like string) produce an index signature. you can see how the Record type is defined here: https://github.com/microsoft/TypeScript/blob/508e52d13a3927806ce1464c2b2d912bd7bb668c/src/lib/es5.d.ts#L1587-L1589

visual hawkBOT
#
type Record<K extends keyof any, T> = {
    [P in K]: T;
};