【发布时间】:2019-11-21 05:47:44
【问题描述】:
TS 抛出奇怪的错误:
错误:(125, 18) TS2569:类型“字符串”不是数组类型或字符串类型。使用编译器选项“--downlevelIteration”来允许迭代器的迭代。
为什么字符串不是字符串?
我想看看 TS 是如何为字符串编译展开运算符的。
我在浏览器控制台中的代码。一个字符串被分解成字符:
> s = 'abcdef';
> r = [...s];
< (6) ["a", "b", "c", "d", "e", "f"]
我在 TS 中的代码:
const s: string = 'abcdef';
const res = [...s]; // <= Error: Type 'string' is not an array type or a string type
console.log(res);
为什么?
TS 版本:
"dependencies": {
"typescript": "^3.5.3"
}
更新:
更新:
我的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"
]
}
【问题讨论】:
-
可能是个愚蠢的问题,但您是否尝试过将
"downlevelIteration": true添加到您的tsconfig中? -
@OliverRadini,是的,我都做了,
true和false。当true符合预期时,TS 不会爆炸。但是为什么它抱怨一个字符串不是字符串呢? -
我只是用 TS
3.5.1复制并粘贴了您的确切示例,没有收到任何警告或错误。 -
您的目标是什么?在TS playground 中,如果我以 ES5 或更低版本为目标,则会出现错误...
-
有certainly an error,但我无法重现
"string" is not a string的任何内容。我刚刚看到“字符串”不是数组”,这是真的。你能在可链接的 Web IDE 中重现错误吗?