TS 错误:类型“字符串”不是数组类型或字符串类型。字符串怎么不是字符串?

Gre*_*een 15 typescript spread-syntax

TS 抛出奇怪的错误:

错误:(125, 18) TS2569:类型“字符串”不是数组类型或字符串类型。使用编译器选项“--downlevelIteration”来允许迭代器迭代。

为什么字符串不是字符串?

我想看看 TS 将如何为字符串编译扩展运算符。

我在浏览器控制台中的代码。一个字符串被分解成字符:

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

我在 TS 中的代码:

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

为什么?

TS版本:

  "dependencies": {
    "typescript": "^3.5.3"
  }
Run Code Online (Sandbox Code Playgroud)

更新:

@VtoCorleone 截图 在此处输入图片说明

更新:

我的 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"
  ]
}

Run Code Online (Sandbox Code Playgroud)

小智 17

扩展异端猴子的评论:

将目标从 更改es5es2015es6修复问题。tsconfig.json为了清楚起见,这是我的全文:

{
  "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"
  ]
}
Run Code Online (Sandbox Code Playgroud)

工作示例

旁注:"downlevelIteration": true也修复了它,但这对我来说似乎不是正确的解决方案。