const arr = [1, 2, 3, 4] as const;
type Arr = typeof arr[number];
// expected & result type : 1 | 2 | 3 | 4
const doubledArr = arr.map(el => el * 2);
type DoubledArr = typeof doubledArr[number];
// expected type : 2 | 4 | 6 | 8
// result type : number
我預計 DoubledArr 型別為 2 | 4 | 6 | 8 由 arr。但是 DoubleArr 型別作為數字出現了。如何將 DoubledArr 型別設為 2 | 4 | 6 | 8.
uj5u.com熱心網友回復:
這種數學轉換不是打字稿可以靜態計算出來的。如果您希望它成為結果型別,則需要對其進行斷言:
const doubledArr = arr.map((el) => el * 2 as 2 | 4 | 6 | 8 );
// OR:
const doubledArr = arr.map((el) => el * 2) as (2 | 4 | 6 | 8)[];
請記住,型別斷言基本上是告訴打字稿“我比你更了解,所以不要在這里檢查我的作業”的一種方式。如果您在斷言中犯了錯誤,打字稿將無法警告您(除非這是一個非常明顯的錯誤)
如果此功能請求得到實施,它可能包括這些功能,但我不希望很快。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/451839.html
標籤:打字稿
上一篇:基于引數的打字稿動態聯合回傳型別
