需求:实现一个通用First<T>,它接受一个数组T并返回它的第一个元素的类型。
type First<T extends readonly any[]> = any
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 a = First<[]>//undefined
type errors = [
// @ts-expect-error
First<'notArray'>,
// @ts-expect-error
First<{ 0: 'arrayLike' }>,
]
先用js的思路写一遍:
- 返回值
- 判断是否是数据,是的话数组进行解构,否则x
function firstNumber(arr){
// arr不是数组 返回never
// return arr[0]
const [first,...rest] = arr
return first