Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#00014 first #5

Open
pkc918 opened this issue Aug 10, 2023 · 0 comments
Open

#00014 first #5

pkc918 opened this issue Aug 10, 2023 · 0 comments

Comments

@pkc918
Copy link
Owner

pkc918 commented Aug 10, 2023

问题

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

就是实现一个 First 将数组中的第一个元素取出来成为新的类型

答案

type First<T extends any[]> = T extends [] ? never : T[0]

讲解

这里利用了 extends 的条件判断,extendsinterface 中作为继承,在type中可以作为条件判断,这里就类似于js中的三元运算

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant