我可以創建一個型別,它接受一個引數N擴展number和一個型別T,并回傳一個包含N組件的元組,每個型別都是T?
例子:
type A<N extends number, T> = [?];
type E1 = A<2, number>; // [number, number]
type E2 = A<3, boolean>; // [boolean, boolean, boolean]
uj5u.com熱心網友回復:
您可以使用帶有可變元組型別的遞回條件型別來實作這一點;例如:
type TupleLen<N extends number, T, A extends any[] = []> =
N extends A['length'] ? A : TupleLen<N, T, [T, ...A]>;
type E1 = TupleLen<2, number>; // [number, number]
type E2 = TupleLen<3, boolean>; // [boolean, boolean, boolean]
當然,編譯器并不允許您對數字文字型別進行任意數學運算,因此上述型別函式很脆弱。如果Ntype 引數是length通過遞回地添加到固定長度元組之前指定的,您將看到一些不幸的行為:
// don't write these unless you like to eat up your CPU
type Oops = TupleLen<-1, number>; // ??????
// error: Type instantiation is excessively deep and possibly infinite.
type Oops2 = TupleLen<0.5, number>; // ??????
// error: Type instantiation is excessively deep and possibly infinite.
人們可以嘗試以TupleLen犧牲復雜性為代價來加強對這種不當用法的抵抗力。我不會在這里討論,因為它可能超出了范圍。無論如何,這意味著你應該小心。
Playground 代碼鏈接
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/439037.html
上一篇:推斷具有默認值的第二種型別
