-
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 练习题第三十四题 #53
Comments
TS中没有直接对比数值的操作,所以需要用 extends 来代替,达到类似的目的,这里默认从一个空数组开始递增,每次判断这个数组的长度和 M,N 是否相同
type SmallerThan<N extends number, M extends number, S extends any[] = [], L = S['length']> =
L extends N
? L extends M ? false : true
: L extends M ? false : SmallerThan<N, M, [...S, 1]>
// 测试用例
type S0 = SmallerThan<0, 1>; // true
type S1 = SmallerThan<2, 0>; // false
type S2 = SmallerThan<8, 10>; // true
type S3 = SmallerThan<5, 5>; // false |
type SmallerThan<
N extends number,
M extends number,
A extends any[] = []
> = A["length"] extends M
? false
: A["length"] extends N
? true
: SmallerThan<N, M, [...A, ""]>
type S0 = SmallerThan<0, 1>; // true
type S1 = SmallerThan<2, 0>; // false
type S2 = SmallerThan<8, 10>; // true
type S3 = SmallerThan<8, 8>; // false 思路: 依然是利用构造数组的长度来判断,体用递归逐步迭代,先和哪个数匹配上,哪个数就小,注意边界问题。 |
|
|
这是来自QQ邮箱的假期自动回复邮件。您好,我最近正在休假中,无法亲自回复您的邮件。我将在假期结束后,尽快给您回复。
|
type SmallerThan<
N extends number,
M extends number,
A extends any[] = []
> = N extends A['length']
? M extends A['length']
? false
: true
: M extends A['length']
? false
: SmallerThan<N, M, [...A, '']>
type S0 = SmallerThan<0, 1>; // true
type S1 = SmallerThan<2, 0>; // false
type S2 = SmallerThan<8, 10>; // true |
type SmallerThan<N extends number,
type S122 = SmallerThan<2, 0>; // false |
这是来自QQ邮箱的假期自动回复邮件。您好,我最近正在休假中,无法亲自回复您的邮件。我将在假期结束后,尽快给您回复。
|
实现一个
SmallerThan
工具类型,用于比较数值类型的大小。具体的使用示例如下所示:The text was updated successfully, but these errors were encountered: