打字稿错误:类型 '[string, unknown][]' 上不存在属性'flat'



我需要在数组上使用.flat((,但Typescript声称:

属性"flat"在类型"[字符串,未知][]"上不存在

我已将"es2019"添加到我的tsconfig文件中:

"lib": ["es2015", "es2019", "dom"],

使用 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);
};

错误仍然存在。如何解决这个问题(这是一个 React 项目,以防万一可能会有所帮助(?

我认为这个问题是因为打字稿无法访问 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"]
}

最新更新