HiveBrain v1.2.0
Get Started
← Back to all entries
principletypescriptCritical

'any' vs 'Object'

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
anyobjectstackoverflow

Problem

I am looking at TypeScript code and noticed that they use:

interface Blablabla {

   field: Object;

}


What is the benefit of using Object vs any, as in:

interface Blablabla {

  field: any;

}

Solution

Object is more restrictive than any. For example:

let a: any;
let b: Object;

a.nomethod(); // Transpiles just fine
b.nomethod(); // Error: Property 'nomethod' does not exist on type 'Object'.


The Object class does not have a nomethod() function, therefore the transpiler will generate an error telling you exactly that. If you use any instead you are basically telling the transpiler that anything goes, you are providing no information about what is stored in a - it can be anything! And therefore the transpiler will allow you to do whatever you want with something defined as any.

So in short

  • any can be anything (you can call any method etc on it without compilation errors)



  • Object exposes the functions and properties defined in the Object class.

Code Snippets

let a: any;
let b: Object;

a.nomethod(); // Transpiles just fine
b.nomethod(); // Error: Property 'nomethod' does not exist on type 'Object'.

Context

Stack Overflow Q#18961203, score: 240

Revisions (0)

No revisions yet.