TypeScript泛型的惊人行为

时间:2018-10-26 13:07:27

标签: typescript

我正在使用泛型,并且期望在下面的代码中在两个地方出现编译错误,但是我没有遇到任何错误。是我以错误的方式使用TypeScript泛型,还是有其他原因导致无法捕获错误的函数调用?

class Person {

}

class Employee extends Person {

}

interface Payable<T> {
  pay(arg: T): T
}

class C implements Payable<Employee> {
  pay(e: Employee) { return e;}
}

const c = new C();

c.pay(123);   // why no errors here?

function doStuff<T extends Employee>(param: T) {

}

doStuff(123);  // why no errors here?

您可以在http://www.typescriptlang.org/play/index.html#src=class%20Person%20%7B%0D%0A%0D%0A%7D%0D%0A%0D%0Aclass%20Employee%20extends%20Person%20%7B%0D%0A%0D%0A%7D%0D%0A%0D%0Ainterface%20Payable%3CT%3E%20%7B%0D%0A%20%20pay(arg%3A%20T)%3A%20T%0D%0A%7D%0D%0A%0D%0Aclass%20C%20implements%20Payable%3CEmployee%3E%20%7B%0D%0A%20%20pay(e%3A%20Employee)%20%7B%20return%20e%3B%7D%0D%0A%7D%0D%0A%0D%0Aconst%20c%20%3D%20new%20C()%3B%0D%0A%0D%0Ac.pay(123)%3B%0D%0A%0D%0Afunction%20doStuff%3CT%20extends%20Employee%3E(param%3A%20T)%20%7B%0D%0A%20%20%0D%0A%7D%0D%0A%0D%0AdoStuff(123)%3B%0D%0A%0D%0A的游乐场中尝试该示例

谢谢

1 个答案:

答案 0 :(得分:0)

由于Employee类没有成员,因此任何值在结构上都与Employee兼容,并且可以在期望Employee的地方传递。参见this FAQ