目的
Github上的类型体操,让你写出更加优雅的TS类型定义,以及探寻TS中我们不熟悉的只是,让我们开始TS的类型挑战把~2022希望通过更文的方式来督促自己学习,每日三题,坚持日更不断~~
题目大纲
01. Easy First of Array
题目要求
import { 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 First<T extends any[]> = T extends [] ? never : T[0];
知识点
A1. 如何获取某个数组中的某个元素?
Q1. 使用索引即可,和JS中类似
2. Easy Length of tuple
题目要求
import { Equal, Expect } from '@type-challenges/utils'
const tesla = ['tesla', 'model 3', 'model X', 'model Y'] as const
const spaceX = ['FALCON 9', 'FALCON HEAVY', 'DRAGON', 'STARSHIP', 'HUMAN SPACEFLIGHT'] as const
type cases = [
Expect<Equal<Length<typeof tesla>, 4>>,
Expect<Equal<Length<typeof spaceX>, 5>>,
// @ts-expect-error
Length<5>,
// @ts-expect-error
Length<'hello world'>,
]
我的解答
type First<T extends any[]> = T extends [] ? never : T[0];
知识点
A1. 为什么这里的数组都是as const?
Q1. 使用as const关键字,会将对应的数组变成readonly,这种时候对应的数组长度不会再变化了,所以这个时候调用length会直接回的对应数组的确切长度~
3. Easy Exclude
题目要求
完成从数组到对象的映射关系
import { Equal, Expect } from '@type-challenges/utils'
type cases = [
Expect<Equal<MyExclude<"a" | "b" | "c", "a">, Exclude<"a" | "b" | "c", "a">>>,
Expect<Equal<MyExclude<"a" | "b" | "c", "a" | "b">, Exclude<"a" | "b" | "c", "a" | "b">>>,
Expect<Equal<MyExclude<string | number | (() => void), Function>, Exclude<string | number | (() => void), Function>>>,
]
我的解答
type MyExclude<T, U> = T extends U ? never : T;
知识点
A1. 如何判断一个联合类型是另一个联合类型的子集?
Q1: 使用extends关键字,如果前面的集合小于后面,就会判断为true