TypeScript Error: Property 'flat' does not exist on type 'string[][]'

Viewed 1602

Property flat does not exist on type string[][]

Several similar questions exist on SO. Their answers are to add es2019 to the --lib tag in the tsconfig.json, but doing this doesn't help my issue.

$ node --version
v14.17.1
$ tsc --version
Version 4.3.5
$ tsc src/index.ts
src/index.ts:6:41 - error TS2550: Property 'flat' does not exist on type 'string[][]'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2019' or later.

6 let flat_array: string[] = nested_array.flat();

src/index.ts

let nested_array: string[][] = [
  ["1", "2"],
  ["3", "4"],
];

let flat_array: string[] = nested_array.flat();

console.log(flat_array);

tsconfig.json

{
    "compilerOptions": {
      "target": "es5",
      "lib": [
        "es2019",
        "DOM"
      ],
      "module": "commonjs",
      "declaration": true,
      "outDir": "./lib",
      "strict": true
    },
    "include": ["src/"],
    "exclude": ["node_modules", "**/__tests__/*"]
  }

I've tried older version of node (v10), and different versions of typescript (3.7.3) too. I've run typescript from dev dependencies as npm script, and using globally installed typescript as well. This error does not go away. I also tried closing and re-opening VSCode.

In case you are interested, here is the package.json file too. I tried running with npm start in addition to globally installed typescript, but this throws the same error.

package.json

{
  "name": "test-typescript",
  "version": "1.0.0",
  "description": "",
  "main": "src/index.ts",
  "scripts": {
    "start": "tsc src/index.ts"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@types/node": "16.3.3",
    "typescript": "4.3.5"
  },
  "dependencies": {}
}

2 Answers

Change target to Es2019. Here is working sample:

{
  "compilerOptions": {
    ...
    "target": "ES2019",
    "module": "ESNext",
    "moduleResolution": "node"
  }
}

Working Code:

PlaygroundLink

And the result:

enter image description here

Running tsc src/idnex.ts won't pick up your tsconfig.json, as stated by the documentation.

# Emit JS for just the index.ts with the compiler defaults
tsc index.ts

(with the compiler defaults)

tsc doesn't support arguments like -p tsconfig.json src/index.ts either. There is no way to compile a single file with tsconfig.json.


Two workarounds:

  1. Specify your compiler options in command line.
  2. Create a new tsconfig.singlefile.json, put your source file in the include option. See this exact same question.
Related