0

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.

1

1 Answer 1

13

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the explanation Nicholas Tower! And why is there no array type...?
What do you imagine array would be that's different from Array? arrays aren't primitives, so it can't be an indication of primitiveness like we have for number, boolean, etc. object exists to fulfill a special role of distinghishing primitives from nonprimitives, but i can't think of an analogous role that array could fulfill.
It's just confusing to mix up Array as a JavaScript interface with these TypeScript types.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.