【发布时间】:2020-11-06 20:32:30
【问题描述】:
我正在寻找可以替换以下功能的简短有效的普通 TypeScript 单行代码:
function arrayOrMemberToArray<T>(input: T | T[]): T[] {
if(Arrary.isArray(input)) return input
return [input]
}
将上述逻辑塞进一个单行三元运算符是非常混乱的,并且在与其他操作链接时很难遵循:
const y = (Array.isArray(input) ? input : [input]).map(() => { /* ... */}) // Too messy
Array.concat 在浏览器控制台中运行良好,但 TS 不允许:
const x: number | number[] = 0
const y = [].concat(x)
Error:(27, 21) TS2769: No overload matches this call.
Overload 1 of 2, '(...items: ConcatArray<never>[]): never[]', gave the following error.
Argument of type 'number' is not assignable to parameter of type 'ConcatArray<never>'.
Overload 2 of 2, '(...items: ConcatArray<never>[]): never[]', gave the following error.
Argument of type 'number' is not assignable to parameter of type 'ConcatArray<never>'.
【问题讨论】:
-
我对Typescript一无所知,也没有安装它,但是像: const y = ((): T[] => [])().concat (x);
标签: javascript arrays typescript one-liner