Typescript抽象可选方法

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上尝试一下。

  • 虽然其他方法可能是以前唯一/最好的方法,但我相信这是前进的正确方法! (2认同)

ids*_*llp 20

您可以使用classinterface合并:

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)

链接到 Typescript 游乐场中的上述代码

  • 这应该是公认的答案 - 您应该明确 Foo 名称必须匹配 - 接口和类名称。 (3认同)
  • 已投票 - 这就是我检查时 React.Component 的实现方式,谢谢 (2认同)

小智 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)


Jos*_*ora 5

抽象的概念是未定义但将在继承的类中的东西.这就是为什么我们不能没有实现的抽象方法.

我建议你创建已经在你的基类中实现的非抽象方法来实现你的目标:

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)

  • 我以为我可以在抽象方法名称中使用`?`运算符. (2认同)