TS2802

error TS2802: Type ‘Set<string>‘ can only be iterated through when using the ‘–downlevelIteration’ flag or with a ‘–target’ of ‘es2015’ or higher.

Broken Code ❌

1
2
3
4
5
6
7
8
9
10
11
12
const data = [
{
code: 'DEU',
country: 'Germany',
},
{
code: 'MAR',
country: 'Morocco',
},
];

const countries = [...new Set(data.map(item => item.country))];
1
2
3
4
5
6
7
8
9
{
"compilerOptions": {
"lib": ["dom", "es5"],
"outDir": "dist",
"rootDir": "src",
"strict": true,
"target": "es5"
}
}

Fixed Code ✔️

In order to resolve the issue, you need to use a higher target environment that is more recent than ES5, such as ES6 for example:

1
2
3
4
5
6
7
8
9
{
"compilerOptions": {
"lib": ["dom", "es5"],
"outDir": "dist",
"rootDir": "src",
"strict": true,
"target": "es6"
}
}

Alternative:

TypeScript will downlevel your code based on your defined “target” to support older JavaScript runtimes that lack built-in iterables. You can enable the downlevelIteration option to ensure compatibility with both legacy and modern platforms. This option generates a helper function that checks if the modern iteration is possible. If it is not supported, the helper function falls back to a legacy iteration, such as index-based iteration.

1
2
3
4
5
6
7
8
9
10
{
"compilerOptions": {
"downlevelIteration": true,
"lib": ["dom", "es5"],
"outDir": "dist",
"rootDir": "src",
"strict": true,
"target": "es5"
}
}