principletypescriptCritical
'any' vs 'Object'
Viewed 0 times
anyobjectstackoverflow
Problem
I am looking at TypeScript code and noticed that they use:
What is the benefit of using
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
anycan be anything (you can call any method etc on it without compilation errors)
Objectexposes the functions and properties defined in theObjectclass.
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.