gpt4 book ai didi

typescript - TS 错误 : Type 'string' is not an array type or a string type. 字符串如何不是字符串?

转载 作者:行者123 更新时间:2023-12-03 15:39:18 25 4
gpt4 key购买 nike

TS 抛出奇怪的错误:

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



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

我想看看 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"
}

更新:

@VtoCorleone
截图
enter image description here

更新:

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

最佳答案

扩展异端猴子的评论:

es5 更改目标至 es2015es6解决了这个问题。这是我的全部 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"
]
}

Working example

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

关于typescript - TS 错误 : Type 'string' is not an array type or a string type. 字符串如何不是字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56990364/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com