TypeScript Object Type vs. {} Type
What is the difference between the Object type and the \{\} type in Typescript?
One of the caveats of Typescript is the need to be compatible with the horrible language Javascript. This means that types may look alike but have rather different behaviour. One of these behaviours is the different of the Object type in Typescript.
Value is assignable to | object | Record<string, unknown> | |
---|---|---|---|
“string” | Yes | No | No |
true | Yes | No | No |
42 | Yes | No | No |
42n | Yes | No | No |
Symbol() | Yes | No | No |
null | No | No | No |
undefined | No | No | No |
() => | Yes | Yes | No |
[1, 2] | Yes | Yes | No |
[] | Yes | Yes | No |
{foo: “bar”} | Yes | Yes | Yes |
Yes | Yes | Yes |
TypeScript is . It is a statically typed superset of JavaScript that brings a lot of advantages to the table, such as better code readability, fewer bugs, and improved developer experience. However, like any other technology, TypeScript has its own set of caveats that developers need to be aware of to make the best use of it.
One of the most notable caveats of TypeScript is the need to be compatible with JavaScript, which can lead to unexpected behavior and inconsistencies. One such example is the difference between the Object type in TypeScript and JavaScript.
In TypeScript, there are three types that are often used interchangeably: , object, and Record<string, unknown>. While these types may look similar, they behave differently depending on the context.
The {} type is the simplest and narrowest type in TypeScript, representing an empty object. It is known as the “empty object type.” It is often used to indicate that an object has no properties.
The object type, on the other hand, is a supertype of all object types in TypeScript. It includes not just plain objects, but also instances of built