我正在寻找可以替换以下功能的简短有效的普通 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>'.