簡體   English   中英

X 類型的參數不能分配給 Y 類型的參數錯誤

[英]Argument of type X is not assignable to parameter of type Y error

此代碼塊出現錯誤:

type Types = {
    foo: (s: string, n: number) => void
    bar: () => void
}
type AbstractType = Record<string, any>

class Class1<GenericType extends AbstractType> {
    public method<T extends keyof GenericType>(event: T, ...data: Parameters<GenericType[T]>) {}
}

class Class2<GenericType extends AbstractType> extends Class1<GenericType & Types> {
    constructor() {
        super()
        // error: Argument of type '[]' is not assignable to parameter of type 'Parameters<(GenericType & Types)["bar"]>'.
        this.method('bar')
    }
}

有人可以幫助修復 TS 錯誤:

Argument of type '[]' is not assignable to parameter of type 'Parameters<(GenericType & Types)["bar"]>'.

如果 Class2 將AbstractType而不是GenericType傳遞給 Class1,則效果很好

class Class2<GenericType extends AbstractType> extends Class1<AbstractType & Types> {}

ts游樂場

您可以像這樣在 class1 中添加一個空數組來解決此問題

class Class1<GenericType extends AbstractType> {
    public method<T extends keyof GenericType>(event: T, ...data: Parameters<GenericType[T]> | []) {}
}

暫無
暫無

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

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