Transpilation appears to dissect a function

I've encountered a strange issue where the transpiler is splitting a single method into two parts:

Before transpiling:

MemberSchema.methods.addAccount = (account: IAccount): void => {
    this.account = new Account({
        ...account,
        isActive: true
    });

    bcrypt.genSalt(parseInt(process.env.SALT_WORK_FACTOR), function(err: Error, salt: any){
        if(err) throw err;

        bcrypt.hash(this.account.password, salt, null, function(err: Error, hash: any){
            if(err) throw err;

            this.account.password = hash;
        });
    });
};

After transpiling:

exports.MemberSchema.methods.addAccount = (account) => {
    this.account = new account_1.Account({}, ...account, isActive, true);
};
bcrypt.genSalt(parseInt(process.env.SALT_WORK_FACTOR), function (err, salt) {
    if (err)
        throw err;
    bcrypt.hash(this.account.password, salt, null, function (err, hash) {
        if (err)
            throw err;
        this.account.password = hash;
    });
});

tsconfig.json:

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "ES6",
    "moduleResolution": "node",
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "types": ["reflect-metadata"],
    "lib": ["ES6"],
    "sourceMap": true,
    "inlineSources": true,
    "pretty": true,
    "outDir": "dist",
    "rootDir": "src",
    "noLib": false,
    "declaration": true
  },
  "include": [
    "src/**/*"
  ],
  "exclude": [
    "node_modules"
  ]
}

Any insights on what may be causing this issue? Is it a configuration adjustment that needs to be made or does it require modifications to the TypeScript file?

Update:

Member.ts:

import { Schema, Model } from "mongoose";
import mongoose = require("mongoose");
import {Account, AccountSchema} from "../Account/account";
import {IAccount} from "../Account/iaccount";
import {isNullOrUndefined} from "util";
import {IMemberModel} from "./imembermodel";

export let MemberSchema: Schema = new Schema({
    account: AccountSchema,
    permissions: [{type: Schema.Types.String, enum: ["regularuser", "admin", "owner"]}],
    isActive: Schema.Types.Boolean
});
MemberSchema.pre("save", next => {
    this.isActive = true;

    next();
    return this;
});
MemberSchema.methods.addAccount = (account: IAccount): void => {
    ***this.account = new Account({
        ...account,
        registrationComplete: true
    });***

    bcrypt.genSalt(parseInt(process.env.SALT_WORK_FACTOR), function(err: Error, salt: any){
        if(err) throw err;

        bcrypt.hash(this.account.password, salt, null, function(err: Error, hash: any){
            if(err) throw err;

            this.account.password = hash;
        });
    });
};
MemberSchema.methods.updateAccount = (account: IAccount): void => {
    if (!isNullOrUndefined(account.password)){
        bcrypt.genSalt(parseInt(process.env.SALT_WORK_FACTOR), function(err: Error, salt: any){
            if(err) throw err;

            bcrypt.hash(this.account.password, salt, null, function(err: Error, hash: any){
                if(err) throw err;

                this.account.password = hash;
            });
        });
    }
};

export const Member: Model<IMemberModel> = mongoose.model<IMemberModel>("Member", MemberSchema);

Member.js:

"use strict";
const mongoose_1 = require("mongoose");
const mongoose = require("mongoose");
const account_1 = require("../Account/account");
const util_1 = require("util");
exports.MemberSchema = new mongoose_1.Schema({
    account: account_1.AccountSchema,
    permissions: [{ type: mongoose_1.Schema.Types.String, enum: ["regularuser", "admin", "owner"] }],
    isActive: mongoose_1.Schema.Types.Boolean
});
exports.MemberSchema.pre("save", next => {
    this.isActive = true;
    next();
    return this;
});
exports.MemberSchema.methods.addAccount = (account) => {
    this.account = new account_1.Account({}, ...account, registrationComplete, true);
};
;
bcrypt.genSalt(parseInt(process.env.SALT_WORK_FACTOR), function (err, salt) {
    if (err)
        throw err;
    bcrypt.hash(this.account.password, salt, null, function (err, hash) {
        if (err)
            throw err;
        this.account.password = hash;
    });
});
;
exports.MemberSchema.methods.updateAccount = (account) => {
    if (!util_1.isNullOrUndefined(account.password)) {
        bcrypt.genSalt(parseInt(process.env.SALT_WORK_FACTOR), function (err, salt) {
            if (err)
                throw err;
            bcrypt.hash(this.account.password, salt, null, function (err, hash) {
                if (err)
                    throw err;
                this.account.password = hash;
            });
        });
    }
};
exports.Member = mongoose.model("Member", exports.MemberSchema);
//# sourceMappingURL=member.js.map

Update 2: The issue seems to be related to the spread operator being used.

When I commented out this line:

this.account = new Account({
            **//...account,**
            registrationComplete: true
        });

It worked as expected. If the spread operator is standard ES6 syntax, why would it cause such a significant transpiling problem?

Answer №1

If you're encountering issues with compiling due to an outdated version of TypeScript that doesn't support the object spread operator (check by running tsc -v and seeing a version of 2.0 or older), it's recommended to update tsc to version 2.1 or higher.

Another possibility is that WebStorm is automatically compiling with an older TypeScript version when you save your file. Refer to their documentation for instructions on upgrading the TypeScript version used for transpilation.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using TypeScript, take advantage of optional chaining in conjunction with object destructuring

After updating typescript to version 3.7.4, I find myself trying to modify my code. My code is straightforward: interface Test event: { queryStringParameters: { [name: string]: string } | null; } } const test:Test = (event) => { // const { n ...

Is there a specific method for conducting a production build using AngularCLI rc.1?

Just recently upgraded to angular-cli version 1.0.0-rc1 by following the guidelines provided on the wiki. The application functions properly when I execute ng serve. Similarly, the app works as expected when I run ng build. However, encountering an issu ...

In Typescript, is it correct to say that { [key: string]: any } is identical to { [key: number]: any }?

Recently diving into Typescript has been an interesting journey, especially when stumbling upon weird language behaviors. After writing the following code snippet, I was surprised to see that it compiled and executed successfully: let x: { [key: string]: a ...

Generating swagger documentation for TypeScript-based Express applications

I have successfully set up the swagger URL following a helpful guide on configuring Swagger using Express API with autogenerated OpenAPI documentation through Swagger. Currently, I am utilizing TypeScript which outputs .js files in the dist folder without ...

Unit Testing in Vue.JS: The original function remains active even after using sinon.stub()

While unit testing my components (which are coded using TypeScript along with vue-class-component), I am utilizing Sinon to stub API calls. However, even after adding the stub to the test, the original method is still being invoked instead of returning the ...

After encountering an error, the puppeteer promptly shuts down the page

During my page testing, an error is thrown by a dependency. Although the error is not critical and does not impact my application, when testing with Puppeteer and encountering this error, it abruptly closes the tested page. How can I bypass this error to c ...

Best practices for safely handling dynamic keys in Typescript

I am searching for a secure method to create keyed objects in this manner: interface Types { RED: 'RED'; BLUE: 'BLUE'; GREEN: 'GREEN'; } type TypeKeys = keyof Types; const COLORS: Types = { RED: 'RED', B ...

Losing concentration when entering a character

Here is the code I am working on. Having an issue with the focus on password, password confirmation, and email inputs within the Sign-up modal. When typing a character, it loses focus automatically. Any suggestions on how to fix this? I have already tried ...

The `createAction` function does not preserve the data type when used with `ofType`

I'm currently developing a mobile application that allows users to choose snacks from a list of available options retrieved from an external API. To handle actions and dispatch API requests, I am utilizing redux-observable. Below is my existing code, ...

Error encountered in Angular: Trying to assign a value to an empty string array results in the error message "Type (string | undefined)[] is not assignable to

Struggling with an issue in my Angular App - trying to assign a value to an empty array Current environment: node 12.18.4 npm 6.14.8 Here's my typescript.ts code snippet: import { Injectable } from "@angular/core"; import { Product } from ...

Displaying Modal from a separate component

CardComponent: export class Card extends Component<Prop, State> { state = { isCancelModalOpen: false, }; marketService = new MarketService(); deleteMarket = () => { this.marketService .deleteMar( ...

Guide to creating a SVG component using typescript in a React application

I have a component where I am passing SVG icons props as an array containing my SVG component data. However, TypeScript is showing me an error while working with Material UI. Type '{ key: number; data: { id: number; icon: ReactNode; }; }' is not ...

Tips for implementing absolute import paths in a library project

In my workspace, I have a library with two projects: one for the library itself and another for a test application. ├── projects    ├── midi-app    └── midi-lib Within the workspace's tsconfig.json file, I set up paths for @a ...

Tips for navigating to a specific item in a react native list?

Is it possible to scroll to a specific element within a list based on another element in the list? For example, if you have a list [a,b,c,d], and each element is a touchableopacity with text a b c d respectively, can you set it up so that clicking on &apos ...

There is no matching overload for this call in React Native

I am working on organizing the styles for elements in order to enhance readability. Here is the code I have written: let styles={ search:{ container:{ position:"absolute", top:0, }, } } After defining the s ...

Configuring Jest with TypeScript: A guide to setting up and running tests across multiple files

Currently, I am diving into the world of TDD and attempting to create a basic test suite for my Node Express API. My project directory has the following structure: . └── root/ ├── src/ │ ├── services/ │ │ └─ ...

What is the best way to eliminate the final character in an input value once it has passed through regex validation in Angular8

Hello! I am attempting to remove the last digit of a string and update the input value each time my function checks if the input value passes a regex test on keypress. Initially, it works correctly, but then it adds an extra digit. After that, it works a ...

Exploring Fetch API with Promise.all

I have successfully implemented a functionality that fetches data from two URLs and performs an action only when both requests are successful. However, I am curious if there is a more efficient and succinct way to achieve the same result. Helper functions ...

The vertical scrolling functionality of the MUI DataGrid in Safari may occasionally fail to work

Utilizing the <Box> component from MUI core and the <DataGrid> component from MUIX, along with some other components, I have created a data grid that has the following appearance: https://i.sstatic.net/Gc8sP.png When the number of rows exceed ...

What is the best way to display loading details during a data loading process within a useEffect hook?

Whenever a specific custom React component I've created is initially mounted, it utilizes useEffect to initiate a lengthy multistep process of loading data that will later be rendered. Since the component isn't always rendered, this costly proces ...