打字稿传递泛型类作为参数

时间:2021-02-21 03:08:21

标签: typescript types parameters

这段代码给我带来了问题:

var makeVariableOfClass = (sentClass: typeof Entity) => {
    var newEntity = new sentClass();
}

interface EntityProps {
    sentient: boolean;
}

class Entity {
    private sentient: boolean;
    constructor(props: EntityProps) {
        this.sentient = props.sentient
    }
}

class Person extends Entity {
    constructor() {
        super({sentient: true});
    }
}

class Wall extends Entity {
    constructor() {
        super({sentient: false});
    }
}

我希望能够以编程方式声明一个人或一堵墙(在本例中),但是在 makeVariableOfClass 中输入 Entity 需要 EntityProps,即使我只想发送事物的一个子集(Person和墙)。我知道我可以将 sentClass 设为 typeof Person | typeof Wall 类型,但我希望比这更具可扩展性。在没有 typeof Person | typeof Wall | typeof ... 的情况下,还有其他方法可以解决这个问题吗?

2 个答案:

答案 0 :(得分:3)

您可以将 sentClass 设为零参数构造函数,返回与 Entity 兼容的内容:

let makeVariableOfClass = <TEntity extends Entity>(
  sentClass: new () => TEntity
) => {
  let newEntity = new sentClass();
  return newEntity;
};

const person = makeVariableOfClass(Person); // person: Person
const wall = makeVariableOfClass(Wall); // wall: Wall
const entity = makeVariableOfClass(Entity); // ERR since Entity does not have a zero-arg constructor
const date = makeVariableOfClass(Date); // ERR since new Date does not produce Entity-compatible value

答案 1 :(得分:0)

我通过发送构造函数来解决它,类似于 y2bd 的答案,但不完全相同:

let makeVariableOfClass = (createNewClass: () => Entity) => {
  return createNewClass();
}

很明显,在这个特定的例子中这有点笨拙,但它有助于我告诉抽象地图类为不同的地图子类使用哪种类型的墙。