Array.flat(无穷大)的正确输入

Proper typing for Array.flat(Infinity)

我了解了新的 Array.flat 方法,并想用它来尝试一下,但返回的类型不是我想要的。

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

const x = hello.flat(Infinity)

这会将 x 的类型设置为:

const x: (number | number[] | number[][])[]

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

我想您一定是在使用带有 new typings for Array.flat(). The main problem here is that TypeScript does not currently have a numeric literal type corresponding to Infinity (see microsoft/TypeScript#32277 的 TypeScript 3.9 测试版 以获得添加此内容的开放建议)。

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

const z = [[[[[[0 as const]]]]]].flat(Infinity);
// const z: (0 | 0[] | 0[][] | 0[][][] | 0[][][][] | 0[][][][][])[]

flat() 的这个问题已在 a comment under microsoft/TypeScript#36554 中指出,该问题充当目前在 TypeScript 中不能完美运行的数组方法的用例集合。如果你真的关心这个,你可能想给它一个,以便人们知道用例正在使用中。


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

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

const x = hello.flat(20); // number[]

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

Playground link to code