TypeScript 编译器接受以下代码而不发出错误信号:
class S {
f(p: number) {
console.log(`${p + 1}`);
}
}
class C extends S {
f(p) {
super.f(p)
}
}
let a: C = new C();
let b: C = new C();
a.f(41); // -> 42
b.f('x'); // -> x1
TypeScript 作为静态类型语言,编译器不应该将继承方法 f
中的 p
参数类型推断为 number
吗?为什么错误类型的字符串值的赋值未被捕获,从而产生奇怪的行为?
最佳答案
class C extends S {
f(p) {
super.f(p)
}
}
此代码等效于此代码:
class C extends S {
f(p: any) { // <---- parameter is 'any'
super.f(p)
}
}
这意味着您可以使用任何参数类型调用C#f
。这是对您的类进行的有效替换,因为派生方法比其基方法更通用是有效的。
这种行为被认为有点违反直觉,因此 there's a feature accepting PRs for this in the language在本例中自动将 p
键入为 string
。
关于inheritance - TypeScript:应该推断继承方法中的参数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36524110/