简体   繁体   English

Typescript 将通用 class 作为参数传递

[英]Typescript passing generic class as parameter

This code is posing a problem to me:这段代码给我带来了一个问题:

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});
    }
}

I'd like to be able to programmatically declare either a person or a wall (in this example), but the typing of Entity in makeVariableOfClass requires the EntityProps, even though I only want to send in a subset of things (Person and Wall).我希望能够以编程方式声明一个人或一面墙(在本例中),但是在 makeVariableOfClass 中键入实体需要 EntityProps,即使我只想发送一部分东西(人和墙) . I understand that I could make sentClass be of type typeof Person | typeof Wall我知道我可以将sentClass设为typeof Person | typeof Wall typeof Person | typeof Wall , but I'd like to be more scalable than that. typeof Person | typeof Wall ,但我想比这更具可扩展性。 Is there another way to get around this without typeof Person | typeof Wall | typeof...没有typeof Person | typeof Wall | typeof...有没有另一种方法来解决这个问题? typeof Person | typeof Wall | typeof... typeof Person | typeof Wall | typeof... ? typeof Person | typeof Wall | typeof...

You could make sentClass be a constructor function with zero parameters that returns something that is compatible with Entity :您可以将sentClass设为构造函数 function ,其参数为零,返回与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

I resolved it by sending in a constructor function, similar to y2bd's answer but not exactly the same:我通过发送构造函数 function 来解决它,类似于 y2bd 的答案,但不完全相同:

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

Obviously this is a bit obtuse in this particular example, but it served my purposes of telling the abstract map class what types of walls to use for different map subclasses.显然,在这个特定示例中这有点迟钝,但它有助于我告诉抽象 map class 不同的 map 子类使用什么类型的墙。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM