Inheritance TypeScript:应推断继承方法中的参数类型
TypeScript编译器在不发出错误信号的情况下接受以下代码:Inheritance TypeScript:应推断继承方法中的参数类型,inheritance,typescript,type-inference,typechecking,Inheritance,Typescript,Type Inference,Typechecking,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 T
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
tonumber
中推断p
的参数类型吗?为什么错误类型的字符串值的赋值没有被捕获,从而产生奇怪的行为
class C extends S {
f(p) {
super.f(p)
}
}
此代码等同于此代码:
class C extends S {
f(p: any) { // <---- parameter is 'any'
super.f(p)
}
}
C类扩展了S类{
f(p:any){//谢谢,Ryan,我同意替换对于更一般的参数是有效的。但是,IMHO,调用super.f(p)
不应该与未定义类型(any)的参数一起使用。有没有办法通过编译器强制执行此类类型检查?