【问题标题】:How can I convert a Set to an Array in TypeScript如何在 TypeScript 中将 Set 转换为数组
【发布时间】:2016-08-18 04:07:26
【问题描述】:

如何在 TypeScript 中将 Set(例如 {2,4,6})转换为数组 [2, 4, 6] 而无需显式编写循环?

我已经尝试了以下这些方法,它们都可以在 JavaScript 中使用,但它们都不能在 TypeScript 中使用

[...set] // ERR: "Type 'Set<{}>' is not an array type" in typescript

Array.from(set) // ERR: Property 'from' does not exist on type 'ArrayConstructor'

【问题讨论】:

  • 你要编译到什么目标? Set 和 Array.from 都是在 ES6 中添加的,在编译到 ES5 时不可用。如果你想使用它们,你可以尝试使用 core.js 为它们获取 polyfils。
  • @toskv 你说得对,当我将目标选项更改为“ES6”时它起作用了,我当前的目标是“ES5”
  • 我现在遇到了一个可能相关的问题,Type 'Set&lt;string&gt;' is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators. ts(2569)mayan anger's answer 帮我解决了。

标签: arrays typescript set typescript1.8


【解决方案1】:

另一种解决方案是使用! 后缀表达式运算符来断言其操作数是非空且非未定义的。

您可以在Non-null assertion operator找到更多信息

您可以使用扩展运算符将 Set 转换为 Array:

const mySet = new Set(['h','j','l','l']);
console.log([...mySet!])

【讨论】:

    【解决方案2】:

    @basarat 的回答对我来说还不够:尽管我的 lib 数组中有 esnext,但我无法使用扩展运算符。

    要在集合和其他 ES2015 可迭代对象上正确启用扩展运算符,我必须启用 downlevelIteration 编译器选项。

    下面是通过tsconfig.json设置的方法:

    {
      "compilerOptions": {
        "downlevelIteration": true
      }
    }
    

    您将在TS documentation page about compiler options 中找到有关此标志的更详细说明。

    【讨论】:

      【解决方案3】:

      或者干脆

      const mySet = new Set<string>();
      mySet.add(1);
      mySet.add(2);
      console.log([...mySet.values()]);
      

      【讨论】:

        【解决方案4】:

        如果你以这种方式声明你的集合:

        const mySet = new Set<string>();
        

        您将能够轻松使用:

        let myArray = Array.from( mySet );
        

        【讨论】:

          【解决方案5】:

          你也可以这样做

          Array.from(my_set.values());
          

          【讨论】:

          • 这应该被标记为正确答案
          【解决方案6】:

          修复

          • 使用 tsconfig.json 和 "lib": ["es6"]

          更多

          【讨论】:

          • 文档链接无效。
          猜你喜欢
          • 2015-06-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-11-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多