类型X的参数不能分配给类型Y的参数(尽管有继承)

时间:2019-10-29 16:07:43

标签: typescript

我正试图找出以下代码无法编译的确切原因:

type IEntityName = 'model1' | 'model2' | 'model3'

class Model {
    id: string

    constructor(id: string) {
        this.id = id
    }
}

class ModelChild1 extends Model { }
class ModelChild2 extends Model { }
class ModelChild3 extends Model { }

const MAP = {
    model1: ModelChild1,
    model2: ModelChild2,
    model3: ModelChild3
}

function getModel(entityName: IEntityName) {
    return MAP[entityName]
}

function doSomethingElse<T extends Model>(model: new () => T) {

}

function doSomething(entityName: IEntityName) {
    const model = getModel(entityName)
    doSomethingElse(model)
}

doSomething('model2')

Playground link

我不了解问题,更重要的是,我不了解如何解决。

1 个答案:

答案 0 :(得分:1)

您缺少构造函数参数类型,应该是:

new (id: string) => T