Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does TypeScript have an equivalent of ES6 "Sets"

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 Set so:

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:

Cannot find name 'Set'

I know I can force VS to ignore it by using

declare var Set;

But I'm hoping for something TypeScript will compile into non-ES6 so that it could be used on older systems.

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:

Uncaught TypeError: (intermediate value).slice is not a function

How can I update my code to use Set in TypeScript?

like image 850
Charles Clayton Avatar asked Jan 21 '17 19:01

Charles Clayton


People also ask

Does TypeScript have sets?

Set is a new data structure introduced in ES6, similar to Map . A typescript Set allows us to store distinct values in a List similar to other programming languages e.g. Java, C#.

Does TypeScript have ES6 features?

TypeScript contains features such as generics and type annotations, Inference, Enums, and Interfaces. ES6 does not support these features. Typescript has three scopes. ES6 has two scopes.

Does TypeScript compile to ES6?

Yes. You can target TypeScript compiler to ES6.

How is TypeScript different from ES6?

TypeScript is a free and open-source programming language. It is developed and maintained by Microsoft. ES6 is a version of ECMAScript (ES), which is a scripting language specification standardized by ECMA international. ES6 will not support.


1 Answers

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();

in any event this code worked for me in my Angular 4 applicaiton

Array.from(new Set(Array)).sort(this.compareNumbers)

hope this helps someone

like image 58
Christian Matthew Avatar answered Oct 08 '22 22:10

Christian Matthew