题目
中文
给定一个正整数作为类型的参数,要求返回的类型是该数字减 1。
例如:
type Zero = MinusOne<1>; // 0
type FiftyFour = MinusOne<55>; // 54
English
Given a number (always positive) as a type. Your type should return the number decreased by one.
For example:
type Zero = MinusOne<1>; // 0
type FiftyFour = MinusOne<55>; // 54
答案
type MinusOne<T extends number, A extends any[] = []> = T extends [
any,
...A
]['length']
? A['length']
: T extends [any, any, ...A]['length']
? [any, ...A]['length']
: MinusOne<T, [0, 0, ...A]>;
支持 T
最大等于2000
, 每次递归时, 数组的长度+2, T = 2000 时, 会产生1000
此的递归, 这也是 typescript 所支持递归深度的极限了