ux.engineer
ux.engineer

Reputation: 11378

TypeScript type 'object' vs Object interface, and why no 'array' type?

Could someone please explain in clear sense why there is a type object in TypeScript, and why would you use it instead of JavaScript Object interface?

Similarly, why is there no array type but rather JavaScript interface Array is used?

It is somewhat confusing to see similar examples over the Internet where Array<Object> and Array<object> are in similar context.

Upvotes: 0

Views: 2637

Answers (1)

Nicholas Tower
Nicholas Tower

Reputation: 85201

object represents anything that's not a primitive; so anything that's not number, string, boolean, symbol, null, or undefined.

Object represents functionality that's common to all objects; so things like .toString() and .valueOf(). But be warned! Because of boxing (boxing is where a primitive gets wrapped in an object), primitives effectively have these properties as well, so the following are perfectly legal:

const a: Object = 5;
const b: Object = "hello";
const c: Object = true;

In contrast, the following would all be errors:

const a: object = 5;
const b: object = "hello";
const c: object = true;

For that reason, Object is almost never what you want to use, and you should use object instead.

See also the Typescript page on Do's and Don'ts

Upvotes: 12

Related Questions