flatten 函数的 TypeScript 类型定义

Iho*_*hor 1 types typescript typescript-typings

我有简单的flatten功能。这个想法是它可以采用字符串数组或字符串数​​组数组,并且始终只返回 1 级字符串数组。例如:

flatten(['a', ['b']]) // returns ['a', 'b']
flatten(['a', 'b']) // returns ['a', 'b']
Run Code Online (Sandbox Code Playgroud)

下面是这个函数的实现

function flatten(arr: ReadonlyArray<string | string[]>): string[] {
   return [].concat(...arr);
}
Run Code Online (Sandbox Code Playgroud)

我收到以下 TypeScript 编译器错误:

  error TS2769: No overload matches this call.
    Overload 1 of 2, '(...items: ConcatArray<never>[]): never[]', gave the following error.
      Argument of type 'string | string[]' is not assignable to parameter of type 'ConcatArray<never>'.
        Type 'string' is not assignable to type 'ConcatArray<never>'.
    Overload 2 of 2, '(...items: ConcatArray<never>[]): never[]', gave the following error.
      Argument of type 'string | string[]' is not assignable to parameter of type 'ConcatArray<never>'.
        Type 'string' is not assignable to type 'ConcatArray<never>'.

  105   return [].concat(...arr);
                        ~~~~~~
Run Code Online (Sandbox Code Playgroud)

如何定义此flatten函数的输入和输出类型?我想避免使用any类型。

jca*_*alz 7

我认为编译器无法弄清楚该[]值应该是什么数组类型。这里最简单的解决方法是告诉它它是string[]带有类型断言的

function flatten(arr: ReadonlyArray<string | string[]>): string[] {
   return ([] as string[]).concat(...arr);
}
Run Code Online (Sandbox Code Playgroud)

希望有所帮助;祝你好运!

Playground 链接到代码