|
| 1 | +import type {If} from './if.d.ts'; |
| 2 | +import type {IfNotAnyOrNever} from './internal/type.d.ts'; |
| 3 | +import type {IsNegative} from './numeric.d.ts'; |
| 4 | +import type {UnknownArray} from './unknown-array.d.ts'; |
| 5 | + |
| 6 | +/** |
| 7 | +Creates a tuple type of the specified length with elements of the specified type. |
| 8 | +
|
| 9 | +@example |
| 10 | +``` |
| 11 | +import type {TupleOf} from 'type-fest'; |
| 12 | +
|
| 13 | +type RGB = TupleOf<3, number>; |
| 14 | +//=> [number, number, number] |
| 15 | +
|
| 16 | +type Line = TupleOf<2, {x: number; y: number}>; |
| 17 | +//=> [{x: number; y: number}, {x: number; y: number}] |
| 18 | +
|
| 19 | +type TicTacToeBoard = TupleOf<3, TupleOf<3, 'X' | 'O' | null>>; |
| 20 | +//=> [['X' | 'O' | null, 'X' | 'O' | null, 'X' | 'O' | null], ['X' | 'O' | null, 'X' | 'O' | null, 'X' | 'O' | null], ['X' | 'O' | null, 'X' | 'O' | null, 'X' | 'O' | null]] |
| 21 | +``` |
| 22 | +
|
| 23 | +Note: If the specified length is the non-literal `number` type, the result will not be a tuple but a regular array. |
| 24 | +
|
| 25 | +@example |
| 26 | +``` |
| 27 | +import type {TupleOf} from 'type-fest'; |
| 28 | +
|
| 29 | +type StringArray = TupleOf<number, string>; |
| 30 | +//=> string[] |
| 31 | +``` |
| 32 | +
|
| 33 | +Note: If the type for elements is not specified, it will default to `unknown`. |
| 34 | +
|
| 35 | +@example |
| 36 | +``` |
| 37 | +import type {TupleOf} from 'type-fest'; |
| 38 | +
|
| 39 | +type UnknownTriplet = TupleOf<3>; |
| 40 | +//=> [unknown, unknown, unknown] |
| 41 | +``` |
| 42 | +
|
| 43 | +Note: If the specified length is negative, the result will be an empty tuple. |
| 44 | +
|
| 45 | +@example |
| 46 | +``` |
| 47 | +import type {TupleOf} from 'type-fest'; |
| 48 | +
|
| 49 | +type EmptyTuple = TupleOf<-3, string>; |
| 50 | +//=> [] |
| 51 | +``` |
| 52 | +
|
| 53 | +@category Array |
| 54 | +*/ |
| 55 | +export type TupleOf<Length extends number, Fill = unknown> = IfNotAnyOrNever<Length, |
| 56 | + _TupleOf<If<IsNegative<Length>, 0, Length>, Fill, []>, |
| 57 | + Fill[], []>; |
| 58 | + |
| 59 | +type _TupleOf<L extends number, Fill, Accumulator extends UnknownArray> = number extends L |
| 60 | + ? Fill[] |
| 61 | + : L extends Accumulator['length'] |
| 62 | + ? Accumulator |
| 63 | + : _TupleOf<L, Fill, [...Accumulator, Fill]>; |
| 64 | + |
| 65 | +export {}; |
0 commit comments