1
头图

Object , {} and object , these three types of representation objects are very confusing. Let's summarize their connections and differences.

Object

Object is the interface definition of Object.prototype . The source code is defined as follows:

 interface Object {
  constructor: Function;
  toString(): string;
  toLocaleString(): string;
  valueOf(): Object;
  hasOwnProperty(v: PropertyKey): boolean;
  isPrototypeOf(v: Object): boolean;
  propertyIsEnumerable(v: PropertyKey): boolean;
}

The prototype chain of all objects in JS inherits from Object.prototype by default, and primitive values have wrapper types. numberstringbooleansymbol 3a44a077ee69c3cfa27152c2777c0800--- 、对象和函数都可以赋值给Object类型。

{}

In JS {} represents a literal object with no own properties. But in TS {} type represents the object type, which can be assigned to the Object type of value can be assigned to the {} type. But the two types are still different. The object assigned to the Object type must strictly satisfy the Object.prototype interface definition, and the assignment to the {} type has no such restriction . as follows:

 // toString() 必须严格满足 Object.prototype.toString() 的定义,返回 string 类型。
// 这里会报错:Type '() => number' is not assignable to type '() => string'.
let a: Object = {
  toString() {
    return 1;
  }
};

let b: {} = {
  toString() {
    return 1;
  }
};

object

To represent objects of non-primitive value types, the object type was introduced in TypeScript 2.2 .除了numberstringbooleansymbolnull undefined , 其他All types can be assigned to the object type. So according to TS's suggestion, when we need to represent an object, just use object , but basically don't need Object and {} .

object is not Object . Always use object !

My JS Blog: Whisper JavaScript


deepfunc
776 声望634 粉丝