我在 Typescript 中學習泛型,我有一個函式,它首先檢查傳入的引數,做一些事情,然后回傳引數。如果我嘗試檢查引數的型別,則沒有問題。
function identity<Type> (arg: Type): Type {
if (typeof(arg) === 'number') console.log('test');
return arg;
}
但是,如果我嘗試將引數與以下值進行比較:
function identity<Type> (arg: Type): Type {
if (arg === 5) console.log('test');
return arg;
}
它拋出一個錯誤說:
generics.ts:2:6 - error TS2367: This condition will always return 'false' since the types 'Type' and 'number' have no overlap.
2 if (arg === 5) console.log('test')
~~~~~~~~~
我不明白為什么它會拋出一個錯誤,說這個條件總是會回傳 false。我認為這可能是真的,我可以傳遞一個正是我正在檢查的值的引數,如果我不能將它與我認為不需要將其與型別進行比較的值進行比較。
uj5u.com熱心網友回復:
這似乎是不正確的 TypeScript 編譯器行為。它已在 4.8.4 中修復。
4.7.4 中的錯誤:游樂場
在 4.8.4 中修復:游樂場
如果您還沒有準備好升級,您可以通過先優化型別來解決問題:
function identity<Type> (arg: Type): Type {
if (typeof(arg) === "number" && arg === 5) console.log('test', arg);
// ^? Type & number
return arg;
}
操場
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/511346.html
上一篇:如何只接受存在型別的特定子型別?
