'object' 、{} 和 TypeScript 中的 Object 之间的区别 [英] Difference between 'object' ,{} and Object in TypeScript

查看:43
本文介绍了'object' 、{} 和 TypeScript 中的 Object 之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图找出 TypeScript 中这两种类型之间的区别:

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

foo: 对象

bar:{}

类型:对象 ?

示例:尝试将 object 分配给假设处理请求标头信息的变量:

Example: trying to assign an object to the variable that suppose to handle headers information for a request:

headers: object;

导致错误:

类型 'object' 不能赋值给 '{ [key: string]: string }`.

Type 'object' is not assignable to '{ [key: string]: string }`.

如果使用 headers: {},同样的条件通过,从而得出结论,{} 的要求稍微不那么严格.

The same condition passes if using headers: {}, which leads to conclusion that {} has some slightly less tight requirements.

推荐答案

TypeScript 有三种容易混淆的类型:Object{}object.

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

如果 strictNullChecks 编译器选项被禁用,您可以将 nullundefined 分配给所有三种类型,否则会发生编译错误.

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

包含所有 JavaScript 对象中存在的内容(如 toString()hasOwnProperty()).任何值(原始的、非原始的)都可以分配给 Object 类型.

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

{} 是一个空对象.它与 Object 相同.

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

object 被引入在 TypeScript 2.2 中.它是任何非原始类型.您不能为其分配任何原始类型,例如 boolnumberstringsymbol.

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 }`"

你会在最后一行得到编译错误.这是因为 { [key: string]: string } 类型比 object 类型更具体.header = strictTypeHeaders 没有任何错误,因为这两种类型都是非原始类型,并且 object 是比 { [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 }

这篇关于'object' 、{} 和 TypeScript 中的 Object 之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆