When to use object, Object, or any

Which type of object to use is a sub-question of the previous one that was discussing the differences between object, Object, and any. The rule of thumb is to always use the more conscribe type. It means to avoid using both object and Object as much as possible. However, in a case where you need to cover a wider range of types and you cannot define them with a union, the use of object is better if you do not need a primitive, because it has less potential values.

Both object and Object are better than any because any allows accessing any members of any type while object will limit you to the following:

let obj1: Object = {};
let obj2: object = {};
let obj3: {} = {};
let obj4: any = {};

obj1.test = "2"; // Does not compile
obj2.test = "2"; // Does not compile
obj3.test = "2"; // Does not compile
obj4.test = "2";

obj1.toString();
obj2.toString();
obj3.toString();
obj4.toString();

If you do not know the type and need to take an object, you should use an object (lowercase) if you are not allowing a primitive. You should fallback to Object (uppercase) if you support a primitive and in the last resort use any. However, a better potential approach is, if possible, to use a generic type that allows avoiding doing a type check and casting, which is often a pitfall of using something such as object and Object.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.28.9