TypeScript:为什么可以将数字分配给 Object 类型的引用? [英] TypeScript: why is a number assignable to a reference of type Object?
问题描述
为什么这是合法的 TypeScript?
Why is this legal TypeScript?
var x: number = 5
var y: Object = x
当然,数字不是 Object
.有人可能会怀疑 x 被隐式强制(自动装箱)到一个对象,但没有:
Surely a number is not an Object
. One might suspect that x is implicitly coerced (auto-boxed) to an object, but no:
if (!(y instanceof Object)) {
console.log(typeof y)
}
印刷品
number
记录:
$ tsc --version
Version 1.8.10
推荐答案
TypeScript 中的类型兼容性基于结构 子类型,而不是名义类型.也就是说,请考虑以下两个接口定义:
Type compatibility in TypeScript is based on structural subtyping, not nominal typing. That said, consider the two following interface definitions:
interface IFoo { X: number }
interface IBar { X: number; Y: number }
IBar
是否扩展了 IFoo
?没有.
Does IBar
extend IFoo
? No.
但是 IFoo
与 IBar
兼容吗?是的.
But is IFoo
compatible with IBar
? Yes.
IFoo
的成员是 IBar
成员的子集,因此您可以将任何 IBar
分配给 IFoo
.但反过来不行:
The members of IFoo
are a subset of IBar
members, thus you can assign any IBar
to IFoo
. But it doesn't work the other way around:
var x: IFoo;
var y: IBar;
x = y // all good
y = x // type error, x has no Y member
这种方式在 Typescript 中所有类型都与 Object
兼容,如果您将其视为空接口.通过这种方式,您可以将任何有效的 typescript 值传递给接受 Object
的函数,并且可以很好地使用 Javascript 库的编写方式.
This way in Typescript all types are compatible with Object
if you think of it as the empty interface. This way you can pass any valid typescript value to functions accepting Object
and play well with the way Javascript libs are written.
我建议阅读文档中的 Type Compatibility 以及关于子类型与分配.
I suggest reading Type Compatibility in docs and the last paragraph about Subtype vs Assignment.
这篇关于TypeScript:为什么可以将数字分配给 Object 类型的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!