Don*_*al0 8 javascript typescript reactjs
我需要在数组上使用 .flat() ,但 Typescript 声称:
类型 '[string, unknown][]' 上不存在属性 'flat'
我已将“es2019 添加到我的 tsconfig 文件中:
"lib": ["es2015", "es2019", "dom"],Run Code Online (Sandbox Code Playgroud)
使用 flat() 的函数是:
const legendSeries = (series) => {
const formattedSeries = {};
series.map((serie) =>
Object.entries(serie).map((s) => {
if (s[0] in formattedSeries) {
return (formattedSeries[s[0]].count += s[1]);
}
return (formattedSeries[s[0]] = { id: s[0], label: s[0], count: s[1] });
})
);
return Object.entries(formattedSeries)
.flat()
.filter((_, i) => i % 2 !== 0);
};Run Code Online (Sandbox Code Playgroud)
错误仍然存在。如何解决这个问题(这是一个 React 项目,以防万一)?
小智 5
我认为这个问题是因为 typescript 无法访问 array.flat(),在这种情况下,它会抛出不了解 flat() 的错误,如@codejockie 上面提到的。您需要更新您的配置文件,如
{
"compilerOptions": {
"target": "es5",
"lib": [
"es2019"
]
}
}
我们需要将 es2019 或 es2019.array 添加到 TypeScript 的 --lib 设置,以便它开始识别 array.flat() 和 flatMap()。
进行更改后。如果更改没有反映,请重新启动您的项目。
将您的更新lib到此"lib": ["es2019", "es2017", "es7", "es6", "dom"]。
这是我的配置:
{
"compilerOptions": {
/* Basic Options */
"target": "es5" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */,
"module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */,
"resolveJsonModule": true,
"lib": [
"es2019",
"es2017",
"es7",
"es6",
"dom"
] /* Specify library files to be included in the compilation. */,
"declaration": true /* Generates corresponding '.d.ts' file. */,
"outDir": "dist" /* Redirect output structure to the directory. */,
/* Strict Type-Checking Options */
"strict": true /* Enable all strict type-checking options. */,
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
/* Advanced Options */
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */,
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
},
"include": ["src/**/*.ts"],
"exclude": ["node_modules", "dist", "examples", "**/*.spec.ts"]
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2944 次 |
| 最近记录: |