【问题标题】:Error TS2339: Property 'entries' does not exist on type 'FormData'错误 TS2339:“FormData”类型上不存在属性“条目”
【发布时间】:2018-11-13 15:05:35
【问题描述】:

我在 Stackoverflow 和网络上进行了搜索,我找到了这个线程 https://github.com/Microsoft/TypeScript/issues/14813,但它并没有解决我的问题。我在使用ng serve --watch 编译代码时遇到了这个错误。

错误 TS2339:“FormData”类型上不存在属性“条目”。

带有fd.entries() 的这部分会触发错误...知道这里发生了什么吗?

onFileSelected(event) {
    const fd = new FormData;

    for (const file of event.target.files) {
        fd.append('thumbnail', file, file.name);

        const entries = fd.entries();
        // some other methods are called here e. g. upload the images

        for (const pair of entries) {
            fd.delete(pair[0]);
        }
    }
}

我看到 (https://github.com/Microsoft/TypeScript/blob/master/src/lib/dom.iterable.d.ts) 有一些 entries 的接口,但不知何故这对我不起作用。

编辑

我的tsconfig.json 看起来像这样

{
    "compileOnSave": false,
    "compilerOptions": {
        "outDir": "./dist/out-tsc",
        "sourceMap": true,
        "declaration": false,
        "moduleResolution": "node",
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "target": "es5",
        "typeRoots": [
            "node_modules/@types"
        ],
        "lib": [
            "es2017",
            "dom"
        ]
    }
}

【问题讨论】:

  • 你能显示你的tsconfig.json的lib数组吗?
  • 我在这个问题上添加了我的tsconfig.json

标签: angular typescript tslint


【解决方案1】:

TypeScript 不支持它,除非你编译到 ES6。

"target": "es5"

如果是es6的话就可以了

【讨论】:

  • 我不认为这是正确的。 new FormData().entries()es6 失败。您是否测试过您的解决方案?
【解决方案2】:

并非所有浏览器都支持entries 方法。如果你无论如何都想使用该方法,并且仍然将目标设置为es5,你可以extend当前界面

declare global {
  interface FormData {
    entries(): Iterator<[USVString, USVString | Blob]>;
  }
}

【讨论】:

  • 对不起,可能是一个 noop 问题...我在哪里放置这个接口?就在文件末尾?我试过了,但这并没有解决错误。我该如何实现这个接口?
  • 你可以把它放在组件类的上面。如果您打算更频繁地使用它,您可以将其导出,也可以将其放在自己的文件中
  • 不幸的是,当我将它放在组件的顶部时,这不起作用。我仍然得到同样的错误error TS2339: Property 'entries' does not exist on type 'FormData'.任何想法?
  • 也许重启cli,因为它倾向于缓存接口/接口变化
  • @webtobesocial 我已经使用declare global 更新了我的答案。您可以将它放在polyfills.ts 的底部,然后您就可以在代码中的任何地方使用FormData.entries()
【解决方案3】:

您需要在tsconfig.json 中的lib 列表中添加“dom.iterable”,例如:

{
  "compilerOptions": {
    "baseUrl": ".",
    "outDir": "build/dist",
    "module": "esnext",
    "target": "es6",
    "lib": [
      "es2019",
      "dom",
      "dom.iterable" // <- there you are
    ],
    // ...
}

【讨论】:

  • 再次“ng serve”。
  • 这是唯一正确的修复方法。在 VSCode 中,您需要运行命令 TypeScript: Restart TS Server 以获取新的库。
  • 我还必须在我的 tsconfig.js 中添加:"downlevelIteration": true,
【解决方案4】:

只需使用 Object().entries(() => ) 语法。

【讨论】:

    猜你喜欢
    • 2016-09-07
    • 2019-01-21
    • 2016-08-13
    • 2017-12-20
    • 2016-11-14
    • 2017-10-24
    • 2021-08-10
    • 2018-11-17
    • 2020-09-25
    相关资源
    最近更新 更多