gpt4 book ai didi

inheritance - TypeScript:应该推断继承方法中的参数类型

转载 作者:搜寻专家 更新时间:2023-10-30 21:42:20 24 4
gpt4 key购买 nike

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 是一种静态类型语言,编译器不应该将继承方法fp 的参数类型推断为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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com