这是官方教程的截图,很明显说的是{name: 'Alice', location: 'Seattle'}是{name: 'Alice'}的子类型。然而文档上怎么说呢,地址截图如下:
https://github.com/Microsoft/...
子类型不能有父类型所不具有的属性。
上面的教程是不是表述的有问题啊
这是官方教程的截图,很明显说的是{name: 'Alice', location: 'Seattle'}是{name: 'Alice'}的子类型。然而文档上怎么说呢,地址截图如下:
https://github.com/Microsoft/...
子类型不能有父类型所不具有的属性。
上面的教程是不是表述的有问题啊
教程表述没有问题,“source function's return type be a subtype of the target type's return type”这句话,其实你可以缩减了看,就认为function's return type不存在,其实就是“source be a subtype of target”。
而,在TypeScript里,subtype的意义和正常理解并不是太相同。
这个要看你第二张图的红框后面一句,if S has no excess properties with respect to T
,是指,如果S
对于T
而言,没有excess property
,就算是它的subtype
。
然而,什么是excess property
呢?
参见这个文档的3.11.5:
A source type S is considered to have excess properties with respect to a target type T if
S is a fresh object literal type, as defined below, and
S has one or more properties that aren't expected in T.
简单而言,只要S中的项,合并到T里面去,不会被T的属性检查排斥,就不算有excess property。相反,如果被T的属性检查排斥,就算有excess property。
因此,在TypeScript中,subtype并不表示数据项少,而是指不存在合并之后会被排斥的属性,就被称为subtype。
对 3.11.5 excess properties 的理解问题。
所以假如是这样才算有多余的属性
x = y;
正确的原因y = x;
错误的原因