ghaiklor / type-challenges-solutions

Solutions for the collection of TypeScript type challenges with explanations
https://ghaiklor.github.io/type-challenges-solutions/
Creative Commons Attribution 4.0 International
474 stars 57 forks source link

type-challenges-solutions/en/easy-first #25

Open utterances-bot opened 3 years ago

utterances-bot commented 3 years ago

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

dvlden commented 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];
likui628 commented 2 years ago

another solution:

type First<T extends any[]> = T extends [infer F, ...infer _] ? F : never
anhuiliujun commented 2 years ago

yet another solution:

type First<T extends any[]> = T['length'] extends 0 ? never : T[0]
AurelienWebnation commented 1 year 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];

@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.

LeeManh commented 1 year ago

Solution use 'infer' :

type First<T extends any[]> = T extends [infer F, ...any[]] ? F : nerver
AurelienWebnation commented 1 year ago

Solution use 'infer' :

type First<T extends any[]> = T extends [infer F, ...any[]] ? F : nerver

@LeeManh Solution already provided by @likui628.

gish commented 9 months ago

This seems to work as well

type First<A> = A extends [infer T, ...any[]] ? T : never;