【问题标题】:Looking for a one-liner to convert x or x[] into x[]寻找一种将 x 或 x[] 转换为 x[] 的单线器
【发布时间】: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


【解决方案1】:

concat 解决方案不进行类型检查,因为数组字面量为空。你需要写

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

或者,您可以使用flat

const arr = [input].flat();

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

【讨论】:

    【解决方案2】:

    不知道为什么你想要一个单行,但你可以只使用三元运算符:

    function arrayOrMemberToArray<T>(input: T | T[]): T[] {
      return Array.isArray(input) ? input : [input];
    }
    

    【讨论】:

    • 单行我的意思是我想用一个简短的单行 sn-p 替换整个函数,就像 Array.concat 示例一样。我编辑了问题以使其更清楚。
    【解决方案3】:

    这似乎有效:

    const x: number | number[] = 0
    const y = ((): number[] => [])().concat(x)
    console.log(y)
    

    【讨论】:

    • 为什么要使用 IIFE?
    • 我对 Typescript 一无所知,也没有在大约 1 分钟前的编辑中看到您的其他答案。
    • @Bergi 所以,这个问题的实际答案是我看到函数 arrayOrMemberToArray 可以将其输出定义为类型化数组,所以......我想也许我可以用箭头函数做同样的事情。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-13
    • 2011-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-14
    • 1970-01-01
    相关资源
    最近更新 更多