首页 > 解决方案 > 寻找一种将 x 或 x[] 转换为 x[] 的单线器

问题描述

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

标签: javascriptarraystypescriptone-liner

解决方案


由于空数组文字,该concat解决方案不会进行类型检查。你需要写

const arr = ([] as number[]).concat(input);

或者,您可以使用flat

const arr = [input].flat();

这不仅更短而且更可取,因为它不依赖于输入的concat-spreadable 属性,而是实际检查数组。


推荐阅读