Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TS Error: Type 'string' is not an array type or a string type. How a string is not a string?

TS throws strange error:

Error:(125, 18) TS2569: Type 'string' is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators.

How comes a string is not a string?

I want to see how TS is going to compile spread operator for a string.

My code in browser console. A string is broken up into characters:

> s = 'abcdef';
> r = [...s];
< (6) ["a", "b", "c", "d", "e", "f"]

My code in TS:

const s: string = 'abcdef';
const res = [...s]; // <= Error: Type 'string' is not an array type or a string type
console.log(res);

Why?

TS version:

  "dependencies": {
    "typescript": "^3.5.3"
  }

UPD:

@VtoCorleone A screenshot enter image description here

UPD:

My tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "downlevelIteration": false,
    "allowJs": true,
    "skipLibCheck": false,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "alwaysStrict": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": false,
    "noEmit": false,
    "sourceMap": true,
    "baseUrl": "./",
    "jsx": "preserve"
  },
  "compileOnSave": true,
  "files": [
    "sample.ts"
  ],
  "exclude": [
    "node_modules",
    "**/*.spec.ts"
  ]
}

like image 849
Green Avatar asked Jul 11 '19 13:07

Green


1 Answers

To expand on Heretic Monkey's comment:

Changing target from es5 to es2015 or es6 fixes the issue. Here's my full tsconfig.json for clarity:

{
  "compilerOptions": {
    "target": "es2015",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
  },
  "exclude": [
    "node_modules"
  ],
  "include": [
    "next-env.d.ts",
    "**/*.ts",
    "**/*.tsx"
  ]
}

Working example

Side note: "downlevelIteration": true also fixed it, but that doesn't seem like the correct solution to me.

like image 147
Andy Mardell Avatar answered Sep 18 '22 23:09

Andy Mardell