2

I have a piece of JS that gets the FormData from a form that is passed into the constructor. This works just fine in JS, but when I translate the same code into TypeScript it doesn't work anymore, and then FormData object is just empty.

Function that generates the FormData:

document.querySelector('#function-form').addEventListener('submit', async e => { 
    e.preventDefault();
    const url = "post/";
    const form =  e.target;
    const formdata = new FormData(form);
    for (var value of formdata.values()) {
      console.log(value); //Correctly prints out values of the form.
    }
})

The same function in TS:

document.querySelector('#function-form').addEventListener('submit', async e => { 
    e.preventDefault();
    const url: RequestInfo = "post/";
    const form: HTMLFormElement = e.target as HTMLFormElement;
    const formdata: FormData = new FormData(form);
    console.log(formdata); //empty
    for (const value of formdata.values()) {
      console.log(value); //Doesn't print anything
    }
})

If it helps, the plan was to write my code in TS and then automatically compile it to JS so that it can be included. If it's needed, I can show the actual compiled TS but I'm not sure if that's required for now.

EDIT: Here is the compiled JS.

var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
var _a;
var _this = this;
(_a = document.querySelector('#function-form')) === null || _a === void 0 ? void 0 : _a.addEventListener('submit', function (e) { return __awaiter(_this, void 0, void 0, function () {
    var url, form, formdata, _i, _a, value, response, data;
    return __generator(this, function (_b) {
        switch (_b.label) {
            case 0:
                e.preventDefault();
                url = "post/";
                form = e.target;
                formdata = new FormData(form);
                console.log(formdata);
                console.log(formdata.entries());
                for (_i = 0, _a = formdata.entries(); _i < _a.length; _i++) {
                    value = _a[_i];
                    console.log("Values: " + value[0] + value[1]);
                }
                return [4 /*yield*/, fetch(url, {
                        method: "POST",
                        mode: "cors",
                        cache: "default",
                        headers: {
                            "X-Requested-With": "XMLHttpRequest",
                            "X-CSRFToken": getCookie("csrftoken"),
                            "Accept": "application/json",
                            "Content-Type": "application/json"
                        },
                        body: JSON.stringify(__spreadArray([], formdata.entries(), true))
                    })];
            case 1:
                response = _b.sent();
                return [4 /*yield*/, response.json()];
            case 2:
                data = _b.sent();
                console.log({ data: data });
                return [2 /*return*/];
        }
    });
}); });

And the config:

{
  "compilerOptions": {
    /* Visit https://aka.ms/tsconfig to read more about this file */

    /* Projects */
    // "incremental": true,                              /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
    // "composite": true,                                /* Enable constraints that allow a TypeScript project to be used with project references. */
    // "tsBuildInfoFile": "./.tsbuildinfo",              /* Specify the path to .tsbuildinfo incremental compilation file. */
    // "disableSourceOfProjectReferenceRedirect": true,  /* Disable preferring source files instead of declaration files when referencing composite projects. */
    // "disableSolutionSearching": true,                 /* Opt a project out of multi-project reference checking when editing. */
    // "disableReferencedProjectLoad": true,             /* Reduce the number of projects loaded automatically by TypeScript. */
    /* Language and Environment */
    "target": "es2016",                                  /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
    // "lib": [],                                        /* Specify a set of bundled library declaration files that describe the target runtime environment. */
    // "jsx": "preserve",                                /* Specify what JSX code is generated. */
    // "experimentalDecorators": true,                   /* Enable experimental support for TC39 stage 2 draft decorators. */
    // "emitDecoratorMetadata": true,                    /* Emit design-type metadata for decorated declarations in source files. */
    // "jsxFactory": "",                                 /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
    // "jsxFragmentFactory": "",                         /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
    // "jsxImportSource": "",                            /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
    // "reactNamespace": "",                             /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
    // "noLib": true,                                    /* Disable including any library files, including the default lib.d.ts. */
    // "useDefineForClassFields": true,                  /* Emit ECMAScript-standard-compliant class fields. */
    // "moduleDetection": "auto",                        /* Control what method is used to detect module-format JS files. */

    /* Modules */
    "module": "commonjs",                                /* Specify what module code is generated. */
    // "rootDir": "./",                                  /* Specify the root folder within your source files. */
    // "moduleResolution": "node",                       /* Specify how TypeScript looks up a file from a given module specifier. */
    // "baseUrl": "./",                                  /* Specify the base directory to resolve non-relative module names. */
    // "paths": {},                                      /* Specify a set of entries that re-map imports to additional lookup locations. */
    // "rootDirs": [],                                   /* Allow multiple folders to be treated as one when resolving modules. */
    // "typeRoots": [],                                  /* Specify multiple folders that act like './node_modules/@types'. */
    // "types": [],                                      /* Specify type package names to be included without being referenced in a source file. */
    // "allowUmdGlobalAccess": true,                     /* Allow accessing UMD globals from modules. */
    // "moduleSuffixes": [],                             /* List of file name suffixes to search when resolving a module. */
    // "resolveJsonModule": true,                        /* Enable importing .json files. */
    // "noResolve": true,                                /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */

    /* JavaScript Support */
    // "allowJs": true,                                  /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
    // "checkJs": true,                                  /* Enable error reporting in type-checked JavaScript files. */
    // "maxNodeModuleJsDepth": 1,                        /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */

    /* Emit */
    // "declaration": true,                              /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
    // "declarationMap": true,                           /* Create sourcemaps for d.ts files. */
    // "emitDeclarationOnly": true,                      /* Only output d.ts files and not JavaScript files. */
    // "sourceMap": true,                                /* Create source map files for emitted JavaScript files. */
    // "outFile": "./",                                  /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
    // "outDir": "./",                                   /* Specify an output folder for all emitted files. */
    // "removeComments": true,                           /* Disable emitting comments. */
    // "noEmit": true,                                   /* Disable emitting files from a compilation. */
    // "importHelpers": true,                            /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
    // "importsNotUsedAsValues": "remove",               /* Specify emit/checking behavior for imports that are only used for types. */
    // "downlevelIteration": true,                       /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
    // "sourceRoot": "",                                 /* Specify the root path for debuggers to find the reference source code. */
    // "mapRoot": "",                                    /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,                          /* Include sourcemap files inside the emitted JavaScript. */
    // "inlineSources": true,                            /* Include source code in the sourcemaps inside the emitted JavaScript. */
    // "emitBOM": true,                                  /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
    // "newLine": "crlf",                                /* Set the newline character for emitting files. */
    // "stripInternal": true,                            /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
    // "noEmitHelpers": true,                            /* Disable generating custom helper functions like '__extends' in compiled output. */
    // "noEmitOnError": true,                            /* Disable emitting files if any type checking errors are reported. */
    // "preserveConstEnums": true,                       /* Disable erasing 'const enum' declarations in generated code. */
    // "declarationDir": "./",                           /* Specify the output directory for generated declaration files. */
    // "preserveValueImports": true,                     /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */

    /* Interop Constraints */
    // "isolatedModules": true,                          /* Ensure that each file can be safely transpiled without relying on other imports. */
    // "allowSyntheticDefaultImports": true,             /* Allow 'import x from y' when a module doesn't have a default export. */
    "esModuleInterop": true,                             /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
    // "preserveSymlinks": true,                         /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
    "forceConsistentCasingInFileNames": true,            /* Ensure that casing is correct in imports. */

    /* Type Checking */
    "strict": true,      
    "strictNullChecks": false,                                /* Enable all strict type-checking options. */
    // "noImplicitAny": true,                         /* When type checking, take into account 'null' and 'undefined'. */
    // "strictFunctionTypes": true,                      /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
    // "strictBindCallApply": true,                      /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
    // "strictPropertyInitialization": true,             /* Check for class properties that are declared but not set in the constructor. */
    // "noImplicitThis": true,                           /* Enable error reporting when 'this' is given the type 'any'. */
    // "useUnknownInCatchVariables": true,               /* Default catch clause variables as 'unknown' instead of 'any'. */
    // "alwaysStrict": true,                             /* Ensure 'use strict' is always emitted. */
    // "noUnusedLocals": true,                           /* Enable error reporting when local variables aren't read. */
    // "noUnusedParameters": true,                       /* Raise an error when a function parameter isn't read. */
    // "exactOptionalPropertyTypes": true,               /* Interpret optional property types as written, rather than adding 'undefined'. */
    // "noImplicitReturns": true,                        /* Enable error reporting for codepaths that do not explicitly return in a function. */
    // "noFallthroughCasesInSwitch": true,               /* Enable error reporting for fallthrough cases in switch statements. */
    // "noUncheckedIndexedAccess": true,                 /* Add 'undefined' to a type when accessed using an index. */
    // "noImplicitOverride": true,                       /* Ensure overriding members in derived classes are marked with an override modifier. */
    // "noPropertyAccessFromIndexSignature": true,       /* Enforces using indexed accessors for keys declared using an indexed type. */
    // "allowUnusedLabels": true,                        /* Disable error reporting for unused labels. */
    // "allowUnreachableCode": true,                     /* Disable error reporting for unreachable code. */
    "downlevelIteration": true,
    /* Completeness */
    // "skipDefaultLibCheck": true,                      /* Skip type checking .d.ts files that are included with TypeScript. */
    "skipLibCheck": true,            
    "lib": [
      "es2015",
      "es2019",
      "dom",
      "dom.iterable",
    ]                /* Skip type checking all .d.ts files. */
  }
}
DeepQuantum
  • 273
  • 3
  • 14
  • Haven't you used your debugger? – Dai Jun 15 '22 at 01:47
  • @Dai I have, and, considering that this issue concerns practically two lines of code, i think there isn't much of value to be gained there, unless you expect me to investigate how the FormData constructor processes the input? As already mentioned in the post, the form is the same in both JS and TS, therefore I'm not really sure what you want me to look at. – DeepQuantum Jun 15 '22 at 02:02
  • 1
    Show us a screenshot of what your debugger's Scope or Watch window says about the `formdata` variable when execution is on the `console.log(formdata)` line. – Dai Jun 15 '22 at 02:03
  • @Phil I write my code in TypeScript. I have an extension in VSCode that automatically executes a command when I save, so I run the compilation at that point and then only include the compiled JS file. And yes, I see my logging, the FormData object appears, but is empty. I also tried to iterate over the `formdata.entries()` iterator but it just doesn't even enter that loop, probably because the length of entries is 0. – DeepQuantum Jun 15 '22 at 02:17
  • @Dai The first image is the FormData object in the watch window, the second screenshoot is the loop that is iterated over, but the loop isn't entered. https://imgur.com/a/LPXatf4 – DeepQuantum Jun 15 '22 at 02:19
  • 1
    @Phil It compiles if you disable `strictNullChecks` - which was the default in older versions of TypeScript. Additionally, from the debugger screenshot I see the `for(of)` is transpiled to `for(_i = 0; _a =...`) which is a hallmark of using the ES3 or ES5 compilation targets so I think they're working with really old code... – Dai Jun 15 '22 at 02:23
  • No repro ~ https://codesandbox.io/s/objective-wind-w2swl2?file=/src/index.ts – Phil Jun 15 '22 at 02:32
  • @Phil @Dai I've added the compiled JS. I'm checking the TypeScript debug output in VSCode and it's saying that `error TS2339: Property 'entries' does not exist on type 'FormData'.`. I haven't changed the TS config, besides adding the libraries at the bottom and adding `downlevelIteration = true` as attempted fixes from (https://stackoverflow.com/questions/50677868/error-ts2339-property-entries-does-not-exist-on-type-formdata)[here] – DeepQuantum Jun 15 '22 at 02:33
  • What exactly is VSCode running to compile your code? Sounds like it's not using your `tsconfig.json` file which can happen if you [specify a particular `.ts` file for `tsc` to compile](https://github.com/microsoft/TypeScript/issues/6591) – Phil Jun 15 '22 at 02:35
  • @Phil `"match": "\\.ts$", "isAsync": true, "cmd": "tsc .\\${file} --outDir static\\js"`. – DeepQuantum Jun 15 '22 at 02:37
  • Does this answer your question? [How to compile a specific file with tsc using the paths compiler option](https://stackoverflow.com/q/44676944/283366) – Phil Jun 15 '22 at 02:41
  • @Phil I'm not sure it does. I'm not quite sure how I would now include the tsconfig. – DeepQuantum Jun 15 '22 at 02:47
  • Remove the `.\\${file}` from your `cmd` – Phil Jun 15 '22 at 02:48
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/245612/discussion-between-deepquantum-and-phil). – DeepQuantum Jun 15 '22 at 02:51

1 Answers1

1

The issue was that the tsconfig.json wasn't set up properly. A couple libraries needed to be included. It was also not in the root of the directory, which it needs to be.

{
  "compilerOptions": {

    /* Language and Environment */
    "target": "es2016",                                  /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */

    /* Modules */
    "module": "commonjs",                                /* Specify what module code is generated. */

    "esModuleInterop": true,                             /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
    // "preserveSymlinks": true,                         /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
    "forceConsistentCasingInFileNames": true,            /* Ensure that casing is correct in imports. */

    /* Type Checking */
    "strict": true,      
    "strictNullChecks": false,                                /* Enable all strict type-checking options. */

    "downlevelIteration": true,
    "skipLibCheck": true,            
    "lib": [
      "es2015",
      "es2019",
      "dom",
      "dom.iterable",
    ]
  }
DeepQuantum
  • 273
  • 3
  • 14