[英]Type "is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'RGT'
[英]Type "is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint" when destructuring generic
我用谷歌搜索了這種情況,但找不到與我的情況相關的答案。 我想要做的是將 function 添加屬性到以通用類型定義的 object。 然后,我想解構那些額外的屬性,並將包含用戶屬性的Record
提供給 function。我理解錯誤的含義,但無法弄清楚為什么它適用於我的情況。 T
永遠不會改變,那么為什么使用Omit
助手會產生這個錯誤呢? (澄清一下,Typescript 在從解構定義類型時使用了Omit
類型)
我用以下代碼重現了錯誤:
type Foo<T extends Record<any, any> = Record<any, never>> = {
key: string;
} & T;
function func<T extends Record<any, any> = Record<any, never>>(
arg0: Foo<T>,
arg1: (props?: T) => any
) {
const { key, ...props } = arg0;
arg1(props);
}
在您的 function func
arg1:(props?:T)
中,與const {key,...props}=arg0
中的解構道具對象不同,因為您通過破壞從arg0
中省略了密鑰key
。
考慮以下 T 的輸入: type SomeType = { key:"abc, data:any }
arg1
將期望類似arg1: (props?: { key:"abc, data:any }) => any
but arg1
永遠不會收到一個 object 以key
作為鍵,因為您在解構時省略了key
。 arg1
將收到(props?: { data:any }) => any
。 所以T.== props(dest.)
當 T 本身包含鍵key
時。
要使其工作,您只需像這樣調整 arg1 的類型注釋。
type Foo<T extends Record<any, any> = Record<any, never>> = {
key: string;
} & T;
function func<T extends Record<any, any> = Record<any, never>>(
arg0: Foo<T>,
arg1: (props?: Omit<T, "key">) => any
) {
const { key, ...props } = arg0;
arg1(props);
//OR
arg1(arg0);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.