awesome-typescript
awesome-typescript copied to clipboard
「重学TS 2.0 」TS 练习题第三十七题
实现一个 Flat
工具类型,支持把数组类型拍平(扁平化)。具体的使用示例如下所示:
type Flat<T extends any[]> = // 你的实现代码
type F0 = Flat<[]> // []
type F1 = Flat<['a', 'b', 'c']> // ["a", "b", "c"]
type F2 = Flat<['a', ['b', 'c'], ['d', ['e', ['f']]]]> // ["a", "b", "c", "d", "e", "f"]
请在下面评论你的答案
type Flat<T extends any[]> = T extends [infer First, ...infer Rest]
? First extends any[]
? [...Flat<First>, ...Flat<Rest>]
: [First, ...Flat<Rest>]
: [];
type F0 = Flat<[]>; // []
type F1 = Flat<["a", "b", "c"]>; // ["a", "b", "c"]
type F2 = Flat<["a", ["b", "c"], ["d", ["e", ["f"]]]]>; // ["a", "b", "c", "d", "e", "f"]
type Flat<T extends any[], S extends any[] = []> = T extends [infer R, ...infer Rest]?
R extends any[] ?
Flat<Rest, Flat<R, S>> :
Flat<Rest, [...S, R]> :
S// 你的实现代码
type F0 = Flat<[]>; // []
type F1 = Flat<["a", "b", "c"]>; // ["a", "b", "c"]
type F2 = Flat<["a", ["b", "c"], ["d", ["e", ["f"]]]]>; // ["a", "b", "c", "d", "e", "f"]
两层递归
type Flat<T extends any[]> =
T extends [infer A, ...infer B]
? [...(A extends any[] ? Flat<A> : [A]), ...Flat<B>]
: []
type F0 = Flat<[]> // []
type F1 = Flat<['a', 'b', 'c']> // ["a", "b", "c"]
type F2 = Flat<['a', ['b', 'c'], ['d', ['e', ['f']]]]> // ["a", "b", "c", "d", "e", "f"]
type Flat<T extends any[]> = T extends [infer A, ...infer Rest] ? A extends [...infer Rest2] ? [...Flat<Rest2>, ...Flat<Rest>] : [A, ...Flat<Rest>] : T // 你的实现代码
type F0 = Flat<[]> // [] type F1 = Flat<['a', 'b', 'c']> // ["a", "b", "c"] type F2 = Flat<['a', ['b', 'c'], ['d', ['e', ['f']]]]> // ["a", "b", "c", "d", "e", "f"]
type Flat<T extends any[]> = T extends [infer F, ...infer R]
? F extends any[]
? [...Flat<F>, ...Flat<R>]
: [F, ...Flat<R>]
: T;
type Flat<T extends any[]> =
T extends [infer P1, ...infer P2]
? [...(P1 extends any[] ? Flat<P1> : [P1]), ...Flat<P2>]
: []
type Flat<T extends any[], U extends any[] = []> =
T['length'] extends 0
? U
: T extends [infer X, ...infer B]
? (X extends [infer D, ...infer E] ? Flat<[...E, ...B], [...U, D]> : Flat<B, [...U, X]> )
: U
type F0 = Flat<[]> // []
type F1 = Flat<['a', 'b', 'c']> // ["a", "b", "c"]
type F2 = Flat<[
'a',
['b', 'c'],
['d', ['e', ['f']]]
]> // ["a", "b", "c", "d", "e", "f"]