Error TS2339: Property 'entries' does not

2019-07-10 02:27发布

问题:

I searched on Stackoverflow and on the web, I found this thread https://github.com/Microsoft/TypeScript/issues/14813 but it does not solve my problem. I run into this error while compiling my code with ng serve --watch.

Error TS2339: Property 'entries' does not exist on type 'FormData'.

This part with fd.entries() triggers the error... any idea what is going on here?

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

I saw that there (https://github.com/Microsoft/TypeScript/blob/master/src/lib/dom.iterable.d.ts) is some interface for entries but somehow this does not work for me.

EDIT

My tsconfig.json looks like this

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

回答1:

TypeScript isn't supporting it unless you are compiling to ES6.

"target": "es5"

If it is es6, then it will work.



回答2:

The method entries is not supported by all browsers. If you want to use the method anyways, and still have the target set to es5, you can extend the current interface

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