Overview
TypeScript 2.2 introduced a new type called object
. It represents any non-primitive type. The following types are considered to be primitive types in JavaScript:
string
boolean
number
bigint
symbol
null
undefined
All other types are considered to be non-primitive types. The new object
type represents exactly these:
|
|
Let’s see how object
lets us write more accurate type declarations.
Type Declarations Using the object
Type
With the release of TypeScript 2.2, the type declarations for the standard library have been updated to make use of the new object
type. For instance, the Object.create()
and Object.setPrototypeOf()
methods now specify the type object | null
for their prototype parameters:
|
|
Passing a primitive value except null as a prototype to either Object.setPrototypeOf()
or Object.create()
results in a TypeError
being thrown at run-time. TypeScript now catches such mistakes and issues an error at compile-time:
|
|
Another use case for the object
type is the WeakMap
data structure that was introduced as part of ES2015. Its keys must be objects and cannot be primitive values. This requirement is now reflected in the type definition:
|
|
object
vs. Object
vs. {}
Perhaps confusingly { 令人迷惑不解地 }, TypeScript defines several types that have a similar name but represent different concepts:
object
Object
{}
We’ve already looked at the new object
type above. Let’s now discuss what Object
and {}
represent.
The Object
Type
TypeScript defines another type with almost the same name as the new object
type, and that’s the Object
type. While object
(lowercased) represents all non-primitive types, Object
(uppercased) describes functionality that is common to all JavaScript objects. That includes the toString()
and the hasOwnProperty()
methods, for example.
Within the lib.es6.d.ts file shipping with TypeScript, the Object
type is defined as follows:
|
|
The Empty Type {}
There’s yet { 还 } another type which is quite similar: {}
, the empty type. It describes an object that has no members on its own. TypeScript issues a compile-time error when you try to access arbitrary properties on such an object:
|
|
However, you can still use all properties and methods defined on the Object
type, which are implicitly available via JavaScript’s prototype chain:
|
|