4

Which is the difference between declaring a field as Array<any> and Array<Object>.

Is there some extra collection tools in typescript?

3 Answers 3

3

An Object in TypeScript is the same thing as in JavaScript.

The difference is that any accepts primitives as well: a number is not an object, unless boxed to a Number.

So while an Array<any> can contain primitives, an Array<Object> can't.

TL;DR: don't use Object.

Source: TypeScript's Do's and Don'ts

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

Comments

3

You are basically asking what's the difference between any and Object and that's answered in the docs about any:

The any type is a powerful way to work with existing JavaScript, allowing you to gradually opt-in and opt-out of type-checking during compilation. You might expect Object to play a similar role, as it does in other languages. But variables of type Object only allow you to assign any value to them - you can’t call arbitrary methods on them, even ones that actually exist:

let notSure: any = 4;
notSure.ifItExists(); // okay, ifItExists might exist at runtime
notSure.toFixed(); // okay, toFixed exists (but the compiler doesn't check)

let prettySure: Object = 4;
prettySure.toFixed(); // Error: Property 'toFixed' doesn't exist on type 'Object'.

Comments

2

Object is the root type for classes and therefore has no properties, except for the inherent properties defined on Object.prototype.

any is a dynamic type and will compile no matter what properties you access on it.

For example:

const a: Object = "Object"
a.length // ERROR

const b: any = "Any"
b.length // Compiles

1 Comment

Well actually Object does have its inherent properties... I understand what you meant but it might be confusing for some.

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.