-
-
Notifications
You must be signed in to change notification settings - Fork 567
/
is-tuple.d.ts
78 lines (61 loc) · 2.01 KB
/
is-tuple.d.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import type {IfAny} from './if-any';
import type {IfNever} from './if-never';
import type {UnknownArray} from './unknown-array';
/**
@see {@link IsTuple}
*/
export type IsTupleOptions = {
/**
Consider only fixed length arrays as tuples.
- When set to `true` (default), arrays with rest elements (e.g., `[1, ...number[]]`) are _not_ considered as tuples.
- When set to `false`, arrays with at least one non-rest element (e.g., `[1, ...number[]]`) are considered as tuples.
@default true
@example
```ts
import type {IsTuple} from 'type-fest';
type Example1 = IsTuple<[number, ...number[]], {fixedLengthOnly: true}>;
//=> false
type Example2 = IsTuple<[number, ...number[]], {fixedLengthOnly: false}>;
//=> true
```
*/
fixedLengthOnly?: boolean;
};
/**
Returns a boolean for whether the given array is a tuple.
Use-case:
- If you want to make a conditional branch based on the result of whether an array is a tuple or not.
Note: `IsTuple` returns `boolean` when instantiated with a union of tuple and non-tuple (e.g., `IsTuple<[1, 2] | number[]>`).
@example
```ts
import type {IsTuple} from 'type-fest';
type Tuple = IsTuple<[1, 2, 3]>;
//=> true
type NotTuple = IsTuple<number[]>;
//=> false
type TupleWithOptionalItems = IsTuple<[1?, 2?]>;
//=> true
type RestItemsNotAllowed = IsTuple<[1, 2, ...number[]]>;
//=> false
type RestItemsAllowed = IsTuple<[1, 2, ...number[]], {fixedLengthOnly: false}>;
//=> true
```
@see {@link IsTupleOptions}
@category Type Guard
@category Utilities
*/
export type IsTuple<
TArray extends UnknownArray,
Options extends IsTupleOptions = {fixedLengthOnly: true},
> =
IfAny<TArray, boolean, IfNever<TArray, false,
TArray extends unknown // For distributing `TArray`
? number extends TArray['length']
? Options['fixedLengthOnly'] extends false
? IfNever<keyof TArray & `${number}`,
TArray extends readonly [...any, any] ? true : false, // To handle cases where a non-rest element follows a rest element, e.g., `[...number[], number]`
true>
: false
: true
: false
>>;