Both types object
and Record<any, any>
appear to me to include the same set of valid objects, which is anything for which typeof x === "object
. Is there any difference between the two?
The object
type is meant to abstract away any keys of an object, whereas Record<K, T>
exists to specifically define the keys of a type. This means there is a difference when trying to access object properties.
TypeScript will allow to access any property of an object of type Record<any, any>
even though the specific keys are not known, since the first generic parameter is any
.
let a: Record<any, any>;
a.foo; // works
On an object of type object
however, the keys are not assumed to be any
. As with Record<any, ...>
, TypeScript does not know which keys actually exist, but it will not allow to access any keys:
let b: object;
a.foo; // error: Property "foo" does not exist on type "object"
Try it in the TypeScript playground.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With