类型提示扩展的抽象类

时间:2019-02-16 00:53:10

标签: typescript react-native

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

如何创建表示道具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 ...,但是肯定有更好的方法吗?

1 个答案:

答案 0 :(得分:2)

  

我该如何创建接口以说prop字符将是扩展AbstractCharacter的类

您可以为此使用通用接口:

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