TypeScript:应该推断继承方法中的参数类型
TypeScript: Parameter type in inherited method should be inferred
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
。这是对您的 class 的有效替换,因为派生方法比其基本方法 更 通用是有效的。
这种行为被理解为有点违反直觉,因此 there's a feature accepting PRs for this in the language 在这种情况下自动将 p
键入 string
。
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
。这是对您的 class 的有效替换,因为派生方法比其基本方法 更 通用是有效的。
这种行为被理解为有点违反直觉,因此 there's a feature accepting PRs for this in the language 在这种情况下自动将 p
键入 string
。