简体   繁体   中英

Typescript error: Property 'flat' does not exist on type '[string, unknown][]'

I need to use.flat() on an array, but Typescript claims:

Property 'flat' does not exist on type '[string, unknown][]'

I've added "es2019 to my tsconfig file:

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

The function where flat() is used is:

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

The error persists. How to fix this (it's a React project in case it might be helpful)?

I think this issue is because typescript doesn't have access to array.flat(), in such a case it will throw an error of not have knowledge of flat(), as mentioned above by @codejockie. You need to update your config file like { "compilerOptions": { "target": "es5", "lib": [ "es2019" ] } }

we need to add es2019 or es2019.array to --lib setting for TypeScript so that it starts recognizing array.flat() and flatMap().

After making the changes. Please restart your project if the changes don't reflect.

Update your lib to this "lib": ["es2019", "es2017", "es7", "es6", "dom"] .

This is my config:

{
  "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"]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM