Typescript类型体操 - Flatten

2022/9/6 23:25:48

本文主要是介绍Typescript类型体操 - Flatten,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

题目

中文

在这个挑战中,你需要写一个接受数组的类型,并且返回扁平化的数组类型。

例如:

type flatten = Flatten<[1, 2, [3, 4], [[[5]]]]> // [1, 2, 3, 4, 5]

English

In this challenge, you would need to write a type that takes an array and emitted the flatten array type.

For example:

type flatten = Flatten<[1, 2, [3, 4], [[[5]]]]> // [1, 2, 3, 4, 5]

答案

type Flatten<T extends any[]> = T extends [infer L, ...infer R]
  ? [...(L extends any[] ? Flatten<L> : [L]), ...Flatten<R>]
  : [];

在线演示



这篇关于Typescript类型体操 - Flatten的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程