1 Star 1 Fork 0

wangzichu/ts-challenges

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
14.第一个元素.ts 1018 Bytes
一键复制 编辑 原始数据 按行查看 历史
WangZiChu199910252255 提交于 2022-11-04 11:22 . 提交
/*
14 - 第一个元素
-------
by Anthony Fu (@antfu) #简单 #array
### 题目
> 欢迎 PR 改进翻译质量。
实现一个通用`First<T>`,它接受一个数组`T`并返回它的第一个元素的类型。
例如:
```ts
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
```
> 在 Github 上查看:https://tsch.js.org/14/zh-CN
*/
/* _____________ 你的代码 _____________ */
type First<T extends any[]> = T extends never[] ? never : T[0]
/* _____________ 测试用例 _____________ */
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' }>,
]
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/wang-zichu/ts-challenges.git
git@gitee.com:wang-zichu/ts-challenges.git
wang-zichu
ts-challenges
ts-challenges
master

搜索帮助