TypeScript: subtyping and covariant argument types

懵懂的女人 提交于 2019-12-08 17:40:03

问题


Common sense suggests that subtyping should be covariant with respect to return type but contravariant with respect to argument types. So, the following should be rejected, because of the strictly covariant argument type of E.f:

interface C {
   f (o: C): void
}

interface D extends C {
   g (): void // give D an extra service
}

class E implements C {
   // implement f with a version which makes stronger assumptions
   f (o: D): void {
      o.g() // rely on the extra service promised by D
   }
}

// E doesn't provide the service required, but E.f will accept
// an E argument as long as I invoke it via C.
var c: C = new E()
console.log('Try this: ' + c.f(c))

Indeed, running the program prints

Uncaught TypeError: o.g is not a function

So: (1) what's the rationale here (presumably there is one, however unsatisfying and JavaScripty); and (2) is there any practical reason why the compiler can't omit a warning in this situation?


回答1:


As per krontogiannis' comment above, when comparing function types, one can be a subtype of the other either because a source parameter type is assignable to the corresponding target parameter type, or because the corresponding target parameter type is assignable to the source parameter type. In the language specification this is called function parameter bivariance.

The reason for permitting bivariant argument types, as opposed to the "naive" expectation of contravariance, is that objects are mutable. In a pure language contravariance is the only sane option, but with mutable objects whether covariance or contravariance makes sense depends on whether you're reading from or writing to the structure. Since there's no way (currently) to express this distinction in the type system, bivariance is a reasonable (albeit unsound) compromise.



来源:https://stackoverflow.com/questions/39569016/typescript-subtyping-and-covariant-argument-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!