我有一个抽象类AbstractCharacter
和具体类:soldier
和knight
以及许多其他字符。
如何创建表示道具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 ...
,但是肯定有更好的方法吗?
答案 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
。