Array.flat(Infinity) 的正确输入

Tho*_*ggi 1 flatten typescript

我了解了新Array.flat方法,并认为我会用它来尝试一下,但返回的类型不是所需的。

const hello = [1, 2, [3], [[4]]]

const x = hello.flat(Infinity)
Run Code Online (Sandbox Code Playgroud)

这将x的类型设置为:

const x: (number | number[] | number[][])[]
Run Code Online (Sandbox Code Playgroud)

我怎样才能拥有这个呢number[]

jca*_*alz 6

我猜您一定正在使用 TypeScript 3.9 的 beta 版本以及Array.flat(). 这里的主要问题是 TypeScript 目前没有对应的数字文字类型Infinity(请参阅microsoft/TypeScript#32277 以获取添加此内容的开放建议)。

目前,TypeScript 中的类型Infinity只是number. 所以编译器不知道array.flat(Infinity)会返回最平坦的数组;相反,它会将其视为您调用了array.flat(num)where numis somenumber值表达式。这意味着它不知道最终的数组有多平坦,并最终为您提供各种可能的平坦深度的联合:

const z = [[[[[[0 as const]]]]]].flat(Infinity);
// const z: (0 | 0[] | 0[][] | 0[][][] | 0[][][][] | 0[][][][][])[]
Run Code Online (Sandbox Code Playgroud)

microsoft/TypeScript#36554下的评论flat()中指出了这个问题,该问题充当目前在 TypeScript 中表现不佳的数组方法的用例集合。如果你真的关心这个,你可能想给它一个,以便人们知道用例正在使用中。


我暂时建议您只传递一个较大的数字常量,其类型可以表示为数字文字。新的类型只能准确到大约大约的深度20,所以你不妨选择这样的东西:

const y = [[[[[[0 as const]]]]]].flat(20);
// const y: 0[]

const x = hello.flat(20); // number[]
Run Code Online (Sandbox Code Playgroud)

好的,希望有帮助;祝你好运!

Playground 代码链接

  • 非常丑陋,但在运行时是正确的:`hello.flat(<20>Infinity)` (2认同)