Open utterances-bot opened 3 years ago
I was struggling to understand what does T extends []
refer to, so I asked on Type Challenge - Discord channel and I got pretty clear response.
Basically it extends empty array, if you try to set T extends unknown[]
it fails, because it means that inside the array, we expect unknown items.
Here's my solution to avoid any[]
and to clarify T extends []
:
type First<T extends Array<unknown>> = T extends Array<never> ? never : T[0];
another solution:
type First<T extends any[]> = T extends [infer F, ...infer _] ? F : never
yet another solution:
type First<T extends any[]> = T['length'] extends 0 ? never : T[0]
I was struggling to understand what does
T extends []
refer to, so I asked on Type Challenge - Discord channel and I got pretty clear response.Basically it extends empty array, if you try to set
T extends unknown[]
it fails, because it means that inside the array, we expect unknown items.Here's my solution to avoid
any[]
and to clarifyT extends []
:type First<T extends Array<unknown>> = T extends Array<never> ? never : T[0];
@dvlden
I prefer this approach personnaly instead of using Array<>
generic type!
type First<T extends unknown[]> = T extends [] ? never : T[0];
But I don't understand why you want to use unknown
instead of any
?
In this case, I think using any is not a mistake, because we accept any type into our array, explicitly.
Solution use 'infer' :
type First<T extends any[]> = T extends [infer F, ...any[]] ? F : nerver
Solution use 'infer' :
type First<T extends any[]> = T extends [infer F, ...any[]] ? F : nerver
@LeeManh Solution already provided by @likui628.
This seems to work as well
type First<A> = A extends [infer T, ...any[]] ? T : never;
First of Array
This project is aimed at helping you better understand how the type system works, writing your own utilities, or just having fun with the challenges.
https://ghaiklor.github.io/type-challenges-solutions/en/easy-first.html