C/C++教程

[Typescript Challenges] 4. Easy - First of Array

本文主要是介绍[Typescript Challenges] 4. Easy - First of Array,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Implement a generic First<T> that takes an Array T and returns it's first element's type.

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

 

/* _____________ Your Code Here _____________ */

type First<T extends any[]> = T extends [infer F, ...(infer RT)] ? F: never


/* _____________ 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' }>,
]

 

这篇关于[Typescript Challenges] 4. Easy - First of Array的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!