繁体   English   中英

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

[英]Argument of type X is not assignable to parameter of type Y (although there's inheritance)

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

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')

游乐场链接

我不明白这个问题,更重要的是,我不明白如何解决它。

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

new (id: string) => T

暂无
暂无

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

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