removing duplicates in an array with new Set gives an error

Viewed 1004

I am trying to remove duplicates in an array with new Set gives an error "new Set(names).slice is not a function"

const names = ["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"];
const uniq = [ ...new Set(names) ];
console.log(uniq);

Here is the code on stackblitz

2 Answers

I was able to fix the error by adding a tsconfig.json in the root of the project. It is a super simple config:

{
  "compilerOptions": {
    "target": "es6"
  }
}

What is happening is that TypeScript is compiling to an es3 version of javascript which is the default if no target is configured as shown here (see --target).

When your code goes through the build phase and is translated from TypeScript to JavaScript, the second line you posted becomes:

var uniq = new Set(names).slice();

Personally I would consider that a TypeScript bug but I never use TypeScript so I can't say for sure.

edit — actually I don't think it happens unless you're targeting ES5.

Related