簡體   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