-
Notifications
You must be signed in to change notification settings - Fork 0
/
firstOfArray.ts
42 lines (31 loc) · 946 Bytes
/
firstOfArray.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
/*
14 - First of Array
-------
by Anthony Fu (@antfu) #easy #array
### Question
Implement a generic `First<T>` that takes an Array `T` and returns its first element's type.
For example:
```ts
type arr1 = ['a', 'b', 'c']
type arr2 = [3, 2, 1]
type head1 = First<arr1> // expected to be 'a'
type head2 = First<arr2> // expected to be 3
```
> View on GitHub: https://tsch.js.org/14
*/
/* _____________ Your Code Here _____________ */
type First<T extends any[]> = T extends [] ? never : T[0];
/* _____________ Test Cases _____________ */
import type { Equal, Expect } from "@type-challenges/utils";
type cases = [
Expect<Equal<First<[3, 2, 1]>, 3>>,
Expect<Equal<First<[() => 123, { a: string }]>, () => 123>>,
Expect<Equal<First<[]>, never>>,
Expect<Equal<First<[undefined]>, undefined>>
];
type errors = [
// @ts-expect-error
First<"notArray">,
// @ts-expect-error
First<{ 0: "arrayLike" }>
];