簡體   English   中英

Typescript 將通用 class 作為參數傳遞

[英]Typescript passing generic class as parameter

這段代碼給我帶來了一個問題:

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 中鍵入實體需要 EntityProps,即使我只想發送一部分東西(人和牆) . 我知道我可以將sentClass設為typeof Person | typeof Wall typeof Person | typeof Wall ,但我想比這更具可擴展性。 沒有typeof Person | typeof Wall | typeof...有沒有另一種方法來解決這個問題? typeof Person | typeof Wall | typeof... typeof Person | typeof Wall | typeof...

您可以將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

我通過發送構造函數 function 來解決它,類似於 y2bd 的答案,但不完全相同:

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

顯然,在這個特定示例中這有點遲鈍,但它有助於我告訴抽象 map class 不同的 map 子類使用什么類型的牆。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM