Difference between 'object' and {} in TypeScript

后端 未结 2 1232
情深已故
情深已故 2020-12-03 00:46

Trying to figure out the difference between these 2 types in TypeScript:

foo: object

and

bar: {}?


Exa

2条回答
  •  北荒
    北荒 (楼主)
    2020-12-03 01:37

    TypeScript has three confusing types: Object, {} and object.

    You can assign null and undefined to all three types if strictNullChecks compiler option is disabled otherwise the compile error occurs.

    Object

    Contains stuff (like toString(), hasOwnProperty()) that is present in all JavaScript objects. Any value (primitive, non-primitive) can be assigned to Object type.

    {}

    {} is an empty object. It is the same as Object.

    object

    object was introduced in TypeScript 2.2. It is any non-primitive type. You can't assign to it any primitive type like bool, number, string, symbol.

    Thus, if you will try this:

    var strictTypeHeaders: { [key: string]: string } = {}; // non-primitive type
    var header: object = {};
    header = strictTypeHeaders; // its OK
    strictTypeHeaders = header; // causes error "Type 'object' is not assignable to type '{ [key: string]: string }`"
    

    you will get the compile error on the last line. This happens because { [key: string]: string } type is more specific than object type. There is no any error on header = strictTypeHeaders since both types are non-primitive and object is more common type than { [key: string]: string }

提交回复
热议问题