Mur*_*göz 3 javascript typescript
我有一个带有一些抽象方法的抽象类.有没有办法将这些方法中的一些标记为可选方法?
abstract class Test {
protected abstract optionalMethod?(): JSX.Element[];
protected abstract requiredMethod(): string;
}
Run Code Online (Sandbox Code Playgroud)
由于某些原因,我可以添加?作为后缀,但它似乎什么都不做,因为我还必须在派生类中实现该方法.现在我正在使用它来标记它可以返回null哪个基本上是可怜的勒芒.
protected abstract optionalMethod?(): JSX.Element[] | null;
Run Code Online (Sandbox Code Playgroud)
Cod*_*rer 49
我不确定这是否在某个时刻发生了变化,但今天(TS 4.3)您可以简单地将基类可选方法设置为非抽象:
abstract class Base {
protected abstract required(): void;
protected optional?(): string;
print(): void {
console.log(this.optional?.() ?? "Base");
}
}
class Child1 extends Base {
protected required(): void { }
}
class Child2 extends Base {
protected required(): void { }
protected optional(): string {
return "Child";
}
}
const c1 = new Child1();
c1.print();
const c2 = new Child2();
c2.print();
Run Code Online (Sandbox Code Playgroud)
在TS Playground上尝试一下。
ids*_*llp 20
您可以使用class并interface合并:
interface Foo {
print?(l: string): void;
}
abstract class Foo {
abstract baz(): void;
foo() {
this.print && this.print('foo');
}
}
class Bar extends Foo {
baz(): void {
if (this.print) {
this.print('bar');
}
}
}
Run Code Online (Sandbox Code Playgroud)
小智 6
Typescript 不支持可选抽象函数的“省略”,但您可以明确地将其保留为未定义,如下所示:
abstract class Test {
protected abstract optionalMethod?(): JSX.Element[];
protected abstract requiredMethod(): string;
}
class MyTest extends Test {
protected optionalMethod: undefined;
protected requiredMethod(): string {
return 'requiredResult';
}
}
Run Code Online (Sandbox Code Playgroud)
抽象的概念是未定义但将在继承的类中的东西.这就是为什么我们不能没有实现的抽象方法.
我建议你创建已经在你的基类中实现的非抽象方法来实现你的目标:
abstract class A {
protected abstract requiredMethod(): string;
protected emptyDefinition(): string | void {};
protected optionalMethod(): string {
return "something optional";
};
}
class B extends A {
protected requiredMethod(): string {
return "something required";
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3476 次 |
| 最近记录: |