TypeScript 是否具有等效于 ES6“Sets”的功能
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41783499/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Does TypeScript have an equivalent of ES6 "Sets"
提问by Charles Clayton
I want to extract all the unique properties from an array of objects, you can do so in ES6 very cleanly using the spread operator and the Setso:
我想从对象数组中提取所有独特的属性,您可以在 ES6 中使用扩展运算符和Set非常干净地执行此操作,因此:
var arr = [ {foo:1, bar:2}, {foo:2, bar:3}, {foo:3, bar:3} ]
const uniqueBars = [... new Set(arr.map(obj => obj.bar))];
>> [2, 3]
However, in TypeScript 1.8.31 this gives me the build error:
但是,在 TypeScript 1.8.31 中,这给了我构建错误:
Cannot find name 'Set'
找不到名称“设置”
I know I can force VS to ignore it by using
我知道我可以通过使用强制 VS 忽略它
declare var Set;
But I'm hoping for something TypeScript will compile into non-ES6 so that it could be used on older systems.
但我希望 TypeScript 能够编译成非 ES6,以便它可以在旧系统上使用。
Does anyone know if there's such a feature I could use?
有谁知道我是否可以使用这样的功能?
Edit:
编辑:
Actually, even when I use declare var Set;, the above code compiles but throws this error repeatedly, so I'm not sure how to use it even without compiling down:
实际上,即使我使用declare var Set;,上面的代码也会编译但反复抛出这个错误,所以即使不编译我也不知道如何使用它:
Uncaught TypeError: (intermediate value).slice is not a function
Uncaught TypeError: (intermediate value).slice 不是函数
How can I update my code to use Setin TypeScript?
如何更新我的代码以Set在 TypeScript 中使用?
采纳答案by toskv
回答by Christian Matthew
This worked for me.
这对我有用。
One of the issues appears to be that typescript trys to use
问题之一似乎是打字稿试图使用
ERROR TypeError: (intermediate value).slice is not a function
instead of Array.from();
而不是 Array.from();
in any event this code worked for me in my Angular 4 applicaiton
无论如何,这段代码在我的 Angular 4 应用程序中对我有用
Array.from(new Set(Array)).sort(this.compareNumbers)
hope this helps someone
希望这有助于某人
回答by Yogesh
You can use this type script library. Or maybe create your one set class using reference from this library
您可以使用此类型脚本库。或者可以使用此库中的参考创建您的一组类

