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

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)