为什么这是合法的 TypeScript?
var x: number = 5
var y: Object = x
一个数字肯定不是一个对象
。有人可能会怀疑 x 被隐式强制(自动装箱)为一个对象,但不是:
if (!(y instanceof Object)) {
console.log(typeof y)
}
打印
number
备案:
$ tsc --version
Version 1.8.10
最佳答案
TypeScript 中的类型兼容性基于结构 子类型,而不是名义类型。也就是说,请考虑以下两个接口(interface)定义:
interface IFoo { X: number }
interface IBar { X: number; Y: number }
IBar
是否扩展 IFoo
?没有。
但是 IFoo
与 IBar
兼容吗?是的。
IFoo
的成员是IBar
成员的子集,因此您可以将任何IBar
分配给IFoo
.但反之则不行:
var x: IFoo;
var y: IBar;
x = y // all good
y = x // type error, x has no Y member
在 Typescript 中,如果您将其视为空接口(interface),则所有类型都与 Object
兼容。通过这种方式,您可以将任何有效的 typescript 值传递给接受 Object
的函数,并且可以很好地使用 Javascript 库的编写方式。
我建议阅读 Type Compatibility在文档和关于子类型与分配的最后一段中。
关于TypeScript:为什么数字可以分配给对象类型的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39562391/