【问题标题】:TypeScript Error: Property 'flat' does not exist on type 'string[][]'TypeScript 错误:类型 'string[][]' 上不存在属性 'flat'
【发布时间】:2021-09-26 07:53:37
【问题描述】:

属性 'flat' 在类型 'string[][]' 上不存在

SO 上存在几个类似的问题。他们的回答是将es2019 添加到tsconfig.json 中的--lib 标记中,但是这样做对我的问题没有帮助。

$ 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__/*"]
  }

我尝试过旧版本的 node (v10),以及不同版本的 typescript (3.7.3)。我已经将开发依赖项中的 typescript 作为 npm 脚本运行,并且还使用了全局安装的 typescript。这个错误不会消失。我也尝试关闭并重新打开 VSCode。

如果您有兴趣,这里也是package.json 文件。除了全局安装的打字稿外,我还尝试使用npm start 运行,但这会引发相同的错误。

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

【问题讨论】:

  • "target": "es5" - 我认为你需要改变这个,而不仅仅是 lib

标签: typescript


【解决方案1】:

将目标更改为Es2019。这是工作示例:

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

工作代码:

PlaygroundLink

结果:

【讨论】:

  • 是的,我看到它在操场上有效。它仍然无法在我的计算机上运行。您的示例中没有“lib”标签。我正在尝试有无等。即使采用您的新配置也无济于事。如何打破 tsconfig.json 文件以确保实际读取新版本?这几乎就像程序没有读取新保存的 tsconfig 文件一样......
  • 如果我保存一个空的 tsconfig.json 文件{},那么我仍然会得到同样的错误。我不应该收到关于 tsconfig.json 文件中缺少信息的不同错误吗??
  • 我在我的 Visual Studio 中使用此配置运行此代码,一切正常。 { "compilerOptions": { "noImplicitAny": false, "noEmitOnError": true, "removeComments": false, "sourceMap": true, "target": "ES2019" }, "exclude": [ "node_modules", "wwwroot" ]
  • 您使用的是哪个版本的打字稿?
  • 是的,我试过你的配置。我开始认为打字稿根本没有读取配置文件。非常令人沮丧。我想我要更新vscode,然后重启。
【解决方案2】:

documentation 所述,运行tsc src/idnex.ts 不会获取您的tsconfig.json

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

使用编译器默认值

tsc 也不支持像 -p tsconfig.json src/index.ts 这样的参数。没有办法用tsconfig.json编译单个文件。


两种解决方法:

  1. 在命令行中指定编译器选项。
  2. 创建一个新的tsconfig.singlefile.json,把你的源文件放在include选项中。看到这个完全相同的question

【讨论】:

    猜你喜欢
    • 2018-05-28
    • 2023-02-21
    • 2019-04-12
    • 2020-07-09
    • 2019-10-20
    • 2023-01-19
    • 2021-09-06
    • 2016-09-07
    • 2020-03-25
    相关资源
    最近更新 更多