pir*_*-gh 11 reduce functional-programming reducers typescript
代码胜于语言,因此:
['a', 'b', 'c'].reduce((accumulator, value) => accumulator.concat(value), []);
Run Code Online (Sandbox Code Playgroud)
该代码非常愚蠢,并返回一个复制的数组...
TS抱怨concat的参数:TS2345:类型'string'的参数不能分配给'ConcatArray'类型的参数。
And*_*dru 16
避免类型转换的更好解决方案:
键入accumulator的值作为string[](和避免一个类型转换上[]):
['a', 'b', 'c'].reduce((accumulator: string[], value) => accumulator.concat(value), []);
Run Code Online (Sandbox Code Playgroud)
在打字稿游乐场中使用此解决方案。
注意事项:
如果可以,应该避免类型转换,因为您正在采用一种类型并将其转换为其他类型。这可能会导致副作用,因为您手动控制将变量强制转换为另一种类型。
此打字稿错误仅在该strictNullChecks选项设置为true. 禁用该选项时,Typescript 错误会消失,但这可能不是您想要的。
我在3.9.2此处引用了使用 Typescript 获得的整个错误消息,以便 Google 为正在搜索答案的人找到此线程(因为 Typescript 错误消息有时会因版本而异):
No overload matches this call.
Overload 1 of 2, '(...items: ConcatArray<never>[]): never[]', gave the following error.
Argument of type 'string' is not assignable to parameter of type 'ConcatArray<never>'.
Overload 2 of 2, '(...items: ConcatArray<never>[]): never[]', gave the following error.
Argument of type 'string' is not assignable to parameter of type 'ConcatArray<never>'.(2769)
Run Code Online (Sandbox Code Playgroud)
Mat*_*t H 12
我相信这是因为for的类型[]推断为never[],这是必须为空的数组的类型。您可以使用类型强制转换来解决此问题:
['a', 'b', 'c'].reduce((accumulator, value) => accumulator.concat(value), [] as string[]);
Run Code Online (Sandbox Code Playgroud)
通常,这不会有太大问题,因为TypeScript会根据您的操作在确定更好的类型以分配给空数组方面做得不错。但是,由于您的示例如前所述是“傻”的,因此TypeScript无法进行任何推断,并将类型保留为never[]。
您应该使用泛型来解决这个问题。
['a', 'b', 'c'].reduce<string[]>((accumulator, value) => accumulator.concat(value), []);
Run Code Online (Sandbox Code Playgroud)
这将设置初始空数组的类型,在我看来这是最正确的解决方案。
| 归档时间: |
|
| 查看次数: |
4271 次 |
| 最近记录: |