I am looking to extract all the distinct properties from an array of objects. This can be done efficiently in ES6 using the spread operator along with the Set object, as shown below:
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, when attempting this in TypeScript 1.8.31, I encountered the following build error:
Cannot find name 'Set'
To work around this, I can use the declaration declare var Set;
to ignore the error.
Is there a way to write this code in TypeScript without relying on ES6 features for compatibility with older systems?
Edit:
Even with using declare var Set;
, the code compiles but throws the following error repeatedly:
Uncaught TypeError: (intermediate value).slice is not a function
How can I modify my code to correctly utilize the Set
object in TypeScript?