30

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?

2
  • 1
    I might be wrong, but I don't think Javascript objects can have keys that are complex types. Although I don't really know what the Record type is capable of.
    – Wingnod
    Sep 9, 2018 at 14:17
  • @Wingnod you are correct. Record is similarly restricted, so my example could have been Record<string | number, any>. Sep 9, 2018 at 18:04

1 Answer 1

26

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.

6
  • 12
    So 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?
    – siwalikm
    Jun 12, 2019 at 5:50
  • 1
    Does this two approaches Record<any, any> and { [key: any}: any } give the same result? Aug 26, 2020 at 12:02
  • 6
    Record is declared as type Record<K extends string | number | symbol, T> = { [P in K]: T; }, so Record<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 use Object<K, V>. Object isn't what it seems to be so TS added Record.
    – José Cabo
    May 3, 2022 at 11:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.