Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Typescript, is there a difference between types `object` and `Record<any, any>`?

Tags:

typescript

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?

like image 539
Behind The Math Avatar asked Sep 09 '18 14:09

Behind The Math


1 Answers

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.

like image 95
Fabian Lauer Avatar answered Nov 13 '22 05:11

Fabian Lauer