抽象静态 javascript 方法解决方法

问题描述 投票:0回答:1

我有课

ChildA
,还有课
ChildB
,还有课
Base

ChildA
ChildB
继承自
Base
Base
的构造函数有 1 个参数,称为
id

我需要添加一个方法,

validate
Base
类,这样:

  1. 每个继承自

    Base
    的类都应该被强制实现。

  2. 此方法将在我拥有

    id
    之前执行,我可以使用它来创建
    ChildA
    /
    ChildB
    的实例。

由于#1,感觉这个方法应该是抽象的。 由于#2,感觉这个方法应该是静态的。 但是,TypeScript 不支持抽象静态函数。

最终,用法应该是从

validate
的其他方法调用
ChildA
ChildB
Base
方法,我们称之为
bla
,类似:

abstract class Base {
    id: string;
    protected static abstract validate(): boolean;

    constructor(id: string) {
        this.id = id;
    }

    bla() {
        const r = (this.constructor as typeof Base).validate();
        // do something with r
    }
}

class ChildA extends Base {
    protected static validate(): boolean {
        // validate stuff
        return true;
    }
}

class ChildB extends Base {
    protected static validate(): boolean {
        // validate stuff
        return false;
    }
}

问题是我无法将

validate
定义为抽象和静态,所以我不确定如何实现我需要的,也许我可以使用接口,但不确定具体如何。

我不是从头开始编写代码,因此我更改内容的自由度有限。

javascript typescript abstract-class
1个回答
0
投票
abstract class Base {
  id: string;
  protected abstract validate(): boolean;

  constructor(id: string) {
    const r = this.bla();

    console.log(r);

    this.id = id;
  }

  bla() {
    const r = this.validate();
    // do something with r
    return r;
  }
}

class ChildA extends Base {
  protected validate(): boolean {
    // validate stuff
    return true;
  }
}

class ChildB extends Base {
  protected validate(): boolean {
    // validate stuff
    return false;
  }
}

const childa = new ChildA('1');
const childb = new ChildB('2');

这应该能够满足您的两个标准。我选择保留方法

protected

  • 每个继承自Base的类都应该被强制实现。

  • 这个方法将在我有一个 id 之前执行,我可以使用它来创建 ChildA / ChildB 的实例。

© www.soinside.com 2019 - 2024. All rights reserved.