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. number
、 string
、 boolean
、 symbol
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 .除了number
、 string
、 boolean
、 symbol
、 null
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 notObject
. Always useobject
!
My JS Blog: Whisper JavaScript
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。