除了使用元組之外,如何確保陣列在函式中傳遞了一定數量的引數
我在打字稿中有一個函式,它接受一個陣列作為引數,當呼叫該函式時,我希望在陣列中傳遞一定數量的元素,除了使用元組之外,我如何實作這一點
type a =(arr: [number, number]) => boolean
const b:a = (arr) => {}
b([]) // should throw an error if the parameter passed in array is less than two
如何在不使用元組的情況下實作這一點
uj5u.com熱心網友回復:
Array<number>
您可以為每個索引使用特定的長度和型別進行擴展:
interface TupleOfTwoNumbers extends Array<number> {
length: 2;
0: number;
1: number;
}
type a = (arr: TupleOfTwoNumbers) => boolean
const b: a = (arr) => true
b([]); // !
b([1]); // !
b([1, 2]); // ok
b([1, 2, 3]); // !
但產生的錯誤沒有那么有用:
“[]”型別的引數不可分配給“TupleOfTwoNumbers”型別的引數。(2345)
與使用元組相比:
'[]' 型別的引數不能分配給 '[number, number]' 型別的引數。源有 0 個元素,但目標需要 2.(2345)
操場
uj5u.com熱心網友回復:
如果您必須這樣做而不是使用元組,您可以length
將陣列的屬性鍵入為您想要的長度,然后它將需要傳遞的陣列的長度來匹配它。
type FixedLengthArray<T, Length extends number = number> = readonly T[] & {
length: Length
}
function foo(arr: FixedLengthArray<number, 3>) {
// Do stuff
}
foo([1, 2, 3, 4] as const);
/*
Argument of type 'readonly [1, 2, 3, 4]' is not assignable to parameter of type 'FixedLengthArray<number, 3>'.
Type 'readonly [1, 2, 3, 4]' is not assignable to type '{ length: 3; }'.
Types of property 'length' are incompatible.
Type '4' is not assignable to type '3'.ts(2345)
*/
as const
需要使陣列的長度固定而不僅僅是plain number
。這反映了現實,因為常規陣列的長度可以更改,因此型別檢查應該失敗,除非它肯定是某個長度。
您可以使用as const
或斷言陣列的型別:
// as const
const arr1 = [1, 2, 3] as const
foo(arr1)
// Type Assertion
type SetLength<T extends any[], Length extends number> = T & {
length: Length;
};
const arr2 = [1, 2, 3]
foo(arr as SetLength<typeof arr, 3>)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/529949.html
標籤:打字稿
上一篇:ts回傳錯誤型別不可分配給型別