[英]Typescript abstract optional method
我有一個帶有一些抽象方法的抽象 class。 有沒有辦法將其中一些方法標記為可選?
abstract class Test {
protected abstract optionalMethod?(): JSX.Element[];
protected abstract requiredMethod(): string;
}
出於某些原因,我可以添加?
作為后綴,但它似乎什么都不做,因為我仍然必須在派生的 class 中實現該方法。現在我像這樣使用它來標記它可以返回null
,這基本上是窮人可選的。
protected abstract optionalMethod?(): JSX.Element[] | null;
您可以通過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');
}
}
}
抽象的概念是未定義但將在繼承的類中的東西。 這就是為什么我們不能有沒有實現的抽象方法。
我建議你創建已經在你的基類中實現的非抽象方法來實現你的目標:
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";
}
}
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';
}
}
我不確定這是否在某個時候發生了變化,但是今天(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();
在TS Playground上試一試。
您不需要界面合並。 您只需要使用沒有默認實現的重載方法,如下所示:
abstract class Test {
...
private someMethod() {
...
this.optinalMethod?.();
}
...
protected abstract requiredMethod(): string;
protected optionalMethod?(): string;
}
abstract 表示它必須在實現 class 中被覆蓋。但是,在可選方法的情況下,我們不想強制覆蓋它。
這已經存在了一段時間,但上面的回答是正確的,但這個例子並不清楚。 您也可以像這樣使用界面合並。
interface Test {
optionalMethod?(): JSX.Element[];
}
abstract class Test {
protected abstract requiredMethod(): string;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.