-
Notifications
You must be signed in to change notification settings - Fork 391
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
「重学TS 2.0 」TS 练习题第三十一题 #50
Comments
type Push<T extends any[], V> = [...T, V];
type Repeat<
T,
C extends number,
R extends Array<any> = []
> = R['length'] extends C ? R : Repeat<T, C, Push<R, T>>;
type R01 = Repeat<0, 0>; // []
type R11 = Repeat<1, 1>; // [1]
type R21 = Repeat<number, 2>; // [number, number]
type R22 = Repeat<string, 5>; // [string, string, string, string, string] |
type Repeat<T, C extends number, A extends any[] = []> = A["length"] extends C
? A
: Repeat<T, C, [...A, T]>;
type R0 = Repeat<0, 0>; // []
type R1 = Repeat<1, 1>; // [1]
type R2 = Repeat<number, 2>; // [number, number] |
和 32 题思路一样 type Repeat<
T,
C extends number,
S extends any[] = [], // 递归判断条件
U extends any[] = [] // 累加记录
> = S['length'] extends C ? U : Repeat<T, C, [...S, 1], [...U, T]>
type R0 = Repeat<0, 0>; // []
type R1 = Repeat<1, 1>; // [1]
type R2 = Repeat<number, 2>; // [number, number] |
type Repeat<T, C extends number, A extends any[] = []> = A["length"] extends C
? A
: Repeat<T, C, [...A, T]>;
type R0 = Repeat<0, 0>; // []
type R1 = Repeat<1, 1>; // [1]
type R2 = Repeat<number, 2>; // [number, number]
type R3 = Repeat<number | string, 3>; // [number | string, number | string, number | string]
type R4 = Repeat<never, 2>; // [never, never]
type R5 = Repeat<any, 2>; // [any, any]
type R6 = Repeat<unknown, 2>; // [unknown, unknown] 思路: 通过extends来判断构造的数组长度是否满足要求 |
|
S 和 U 是否使用一个就行 |
type _Repeat<
T,
C extends number,
List extends T[] = []
> = List["length"] extends C ? List : _Repeat<T, C, [...List, T]>;
type Repeat<T, C extends number> = _Repeat<T, C, []>; |
为什么我的 |
type Repeat<T, C extends number, R extends any[] = []> = R['length'] extends C ? R : Repeat<T, C, [T, ...R]> // 你的实现代码 type R0 = Repeat<0, 0>; // [] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
实现一个
Repeat
工具类型,用于根据类型变量C
的值,重复T
类型并以元组的形式返回新的类型。具体的使用示例如下所示:The text was updated successfully, but these errors were encountered: