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?
1 Answer
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.
-
12So why would I ever want to use
object
, if that effectively precludes me from accessing any of the properties? Sep 9, 2018 at 18:02 -
@BehindTheMath One use-case can be if you're writing a polyfill for your native js object. You still would want the method names, their return types etc. to be respected right?– siwalikmJun 12, 2019 at 5:50
-
1Does this two approaches
Record<any, any>
and{ [key: any}: any }
give the same result? Aug 26, 2020 at 12:02 -
6
Record
is declared astype Record<K extends string | number | symbol, T> = { [P in K]: T; }
, soRecord<A, B>
is equivalent to{ [key: A]: B; }
Aug 26, 2020 at 12:36 -
The other reason
Record<K, V>
exists in TS is because we can't useObject<K, V>
.Object
isn't what it seems to be so TS added Record. May 3, 2022 at 11:23
Record<string | number, any>
.