类型暗示扩展的抽象类



我有一个抽象类AbstractCharacter和具体类:soldierknight,以及许多其他字符。

如何创建接口,说Prop character将是扩展AbstractCharacter

的类

,例如

export abstract class AbstractCharacter {
    public abstract name: string;
    public abstract hp: number;
}
export class Soldier extends AbstractCharacter {
    public name = "Soldier";
    public hp = 100;
}
class Knight extends AbstractCharacter {
    public name = "Knight";
    public hp = 100;
}

和用法:

interface IFormationCharacter {
  character: T extends AbstractCharacter // this doesn't work because T doesn't exist
  character: typeof AbstractCharacter // this doesn't allow for extending, i.e. new character() will say "Cannot create an instance of abstract class"
}
export default class FormationCharacter extends React.Component<IFormationCharacter> {
  constructor(props: IFormationCharacter) {
    super(props);

我知道我可以做typeof Knight | typeof Soldier | typeof ...,但肯定必须有更好的方法?

如何创建界面来说prop字符将是扩展抽象character

的类

您可以使用通用接口:

interface IFormationCharacter<T extends AbstractCharacter> {
  character: T;
}

然后,您将必须将接口与类型的参数一起使用:

IFormationCharacter<Knight>
IFormationCharacter<Soldier>
// or keep it generic
export default class FormationCharacter<T> extends React.Component<IFormationCharacter<T>> {
  constructor(props: IFormationCharacter<T>) {
    super(props);

根据您的需求,最好的可能是坚持使用抽象属性character: AbstractCharacter

相关内容

  • 没有找到相关文章

最新更新