[英]Union of types was reduced to 'never' breaks typing: Type was reduced to 'never' because property has conflicting types in some constituents
[英]Proxy property in setter has never type
使用 TypeScript 4.5.4(當前最新)和當前 Nightly 版本,此代碼(見下文或TypeScript 操場)拋出錯誤Type 'any' is not assignable to type 'never'.(2322)
版本 1、2 3,4 版本 5 和 6 尚未報告錯誤。 如果我們刪除num
prop 或str
之一,所有錯誤都消失了。
這個設計有解釋嗎?
const myObj = {
num: -1,
arr: [1, 2, 3],
str: '',
};
const proxy = new Proxy(myObj, {
set(target, prop: keyof typeof myObj, value) {
/* none of these works */
// Ver. 1
if (prop in target) target[prop] = value;
// Ver. 2
target[prop] = value;
// Ver. 3
target[prop as keyof typeof myObj] = value;
// Ver. 4
switch (prop) {
case 'num':
case 'str':
target[prop] = value;
break;
}
/* while these works */
// Ver. 5
switch (prop) {
case 'num':
target[prop] = value;
break;
case 'str':
target[prop] = value;
break;
}
// Ver. 6
switch (prop) {
case 'num':
target[prop] = value;
break;
default:
target[prop] = value;
break;
}
return true;
},
});
console.log('proxy : ', proxy);
寫作在 TS 中產生類型交集。
這是官方 repo microsoft/TypeScript#47295答案的副本,這是“按預期工作”的功能。
在您的大多數設置中,
prop
的類型不會從"num" | "str" | "arr"
縮小范圍。"num" | "str" | "arr"
"num" | "str" | "arr"
; 由於您正在寫入target[prop]
而不是從中讀取,因此會產生它可以引用的所有可能類型的交集(不是聯合)。 如果沒有重疊,則交集將折疊為never
,因為沒有可能的值適用於所有這些。
創建此答案是為了結束問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.