typescript教程上的这句话是不是错了

图片描述
这是官方教程的截图,很明显说的是{name: 'Alice', location: 'Seattle'}是{name: 'Alice'}的子类型。然而文档上怎么说呢,地址截图如下:
https://github.com/Microsoft/...
图片描述

子类型不能有父类型所不具有的属性。
上面的教程是不是表述的有问题啊

阅读 2.6k
2 个回答

3.11.5 excess properties 的理解问题。

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.

所以假如是这样才算有多余的属性

x = {name: "Alice", location: "Seattle"}

x = y; 正确的原因

S is an object type, an intersection type, an enum type, or the Number, Boolean, or String primitive type, T is an object type, and for each member M in T, one of the following is true:

  • M is a property and S has an apparent property N where

    • M and N have the same name,

    • the type of N is a subtype of that of M,

    • M and N are both public, M and N are both private and originate in the same declaration, M and N are both protected and originate in the same declaration, or M is protected and N is declared in a class derived from the class in which M is declared.

y = x; 错误的原因

S is an object type, an intersection type, an enum type, or the Number, Boolean, or String primitive type, T is an object type, and for each member M in T, one of the following is true:

  • M is a property and S has an apparent property N where

    • M and N have the same name,

    • the type of N is a subtype of that of M,

    • M and N are both public, M and N are both private and originate in the same declaration, M and N are both protected and originate in the same declaration, or M is protected and N is declared in a class derived from the class in which M is declared.

教程表述没有问题,“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。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进