gpt4 book ai didi

typescript - 允许子类使用函数属性或方法覆盖

转载 作者:行者123 更新时间:2023-12-02 14:53:53 28 4
gpt4 key购买 nike

class Foo {
foo: () => void
}

class Bar extends Foo {
foo() {}
}

有没有办法告诉 TypeScript 允许上面的例子?

Playground

Class 'Foo' defines instance member property 'foo', but extended class 'Bar' defines it as instance member function.

最佳答案

那是因为您可以调用父方法,但不能调用父实例成员。

原因是适当的方法被保存到原型(prototype)链中,而成员函数则没有。

class Foo {
foo() {
return `Successfully called Foo.foo()`;
}

bar = () => {
return `Successfully called Foo.bar()`;
}
}

console.log(
('foo' in Foo.prototype), // true (methods are correctly inherited)
('bar' in Foo.prototype), // false (instance properties are not inherited)
);

如果该属性不在属性链中,则尝试使用 super 调用它会导致运行时错误。

class Bar extends Foo {
foo = () => {
return super.foo(); // Good: `foo` is in the prototype chain
}

bar = () => {
return super.bar(); // Runtime error: `bar` is not in the prototype chain
}
}

这使得从方法转到类实例属性(这里:foo)是安全的,但反过来就不安全了。

关于typescript - 允许子类使用函数属性或方法覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53997107/

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