What is the best approach to deactivate or manage init and toJSON functionalities?

After creating a .NET core 2.2 webapi and utilizing swagger / nswag to generate the API for my React / typescript application, I encountered a ts(2739) message when attempting to set up a new object:

Type '{ firstName: string; lastName: string; }' is missing the following properties from type 'User': init, toJSON

Is there a way to globally disable or handle this issue? It functions correctly, but I would prefer to eliminate the error (perhaps with a ts-ignore?).

I've tested various solutions like the following;

Error but data is read:

const newUser: User = {
                firstName,
                lastName,
            };

No error but data is not read:

const newUser = new User ({
                firstName,
                lastName,
            });

An alternative would be to remove all nswag created init and toJSON methods, but that would be too time-consuming.

.NETCore Model (Baseclass is simply the Id and createdAtDate)

    public class User : BaseModel
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Image { get; set; }
    }
}

Generated Typescript Nswag Code

export interface IBaseModel {
    id?: string | null;
    creationDate?: Date | null;
    updateDate?: Date | null;
}

export class User extends BaseModel implements IUser {
    firstName?: string | null;
    lastName?: string | null;
    image?: string | null;

    constructor(data?: IUser) {
        super(data);
    }

    init(data?: any) {
        super.init(data);
        if (data) {
            this.firstName = data["firstName"] !== undefined ? data["firstName"] : <any>null;
            this.lastName = data["lastName"] !== undefined ? data["lastName"] : <any>null;
            this.image = data["image"] !== undefined ? data["image"] : <any>null;
        }
    }

    static fromJS(data: any): User {
        data = typeof data === 'object' ? data : {};
        let result = new User();
        result.init(data);
        return result;
    }

    toJSON(data?: any) {
        data = typeof data === 'object' ? data : {};
        data["firstName"] = this.firstName !== undefined ? this.firstName : <any>null;
        data["lastName"] = this.lastName !== undefined ? this.lastName : <any>null;
        data["image"] = this.image !== undefined ? this.image : <any>null;
        super.toJSON(data);
        return data;
    }
}

export interface IUser extends IBaseModel {
    firstName?: string | null;
    lastName?: string | null;
    image?: string | null;
}

Typescript use class as type

const newUser: User = {
                firstName,
                lastName,
            };

I seek to disable the init and toJSON methods that are causing the error, without having to declare them to function.

Error:

Type '{ firstName: string; lastName: string; }' is missing the following properties from type 'User': init, toJSON

I want to resolve the errors without manually rewriting the entire NSWAG generated API client. Perhaps I am mishandling the classes; when using the interfaces, I receive the same error message.

Answer №1

When you create a TypeScript file with DTO style set as Class, it automatically generates the <code>init
and toJSON methods. However, if you choose Interface style, only properties will be included without any implemented methods. For more information, refer to the screenshot below: DTO settings

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

New feature in Next.js 13: Utilizing a string within className

Looking for a way to dynamically generate radio buttons in Next.js using a list of strings? Utilizing Tailwind CSS classes, you can modify the appearance of these buttons when checked by leveraging the peer/identifier classname. But how do you include th ...

What is the reason for requiring that the value type in a map must be uniform?

When using TypeScript, I expect the map type to be either a number or string, but unfortunately, an error is being reported. Click here for the Playground const map: Map<string, string | number> = new Map([ [ '1', &apo ...

How to declare and initialize a variable in Angular 2 using TypeScript

I'm currently working with angular 2 and I'm having trouble understanding how to set a variable. The variable _isLoading is being set in "this.observable.filter((event)" but it doesn't seem to change in the template. This is my TypeScript co ...

Is your Typescript struggling to infer types correctly?

I created a function that converts an Array into a Map: function toMap<T,TKey,TElement>(items: Array<T>, keySelector: (item: T) => TKey, elementSelector: (item: T) => TElement ): Map<TKey,TElement> { var ma ...

Dynamic form groups in Angular: Avoiding the issue of form inputs not binding to form groups

Purpose My goal is to develop a dynamic form in Angular that adjusts its fields based on an array received from the backend. For example, if the array contains ["one", "two", "three", "four"], the form should only ...

Transform Sass modules into css during the creation of a component library

I'm in the process of developing a React TypeScript component library that will be utilized in various projects. Currently, I have been using the following script to build this project. "build": "rimraf dist && NODE_ENV=product ...

Undefined Perception

Trying to obtain values from an observable, my subscription code within the component looks like this: this.checkoutService.getDisabledDate().subscribe (dates=>{this.formattedDate=dates}, (error:any)=>{console.log(error)}); When logging this.forma ...

Checkbox selection limitation feature not functioning correctly

Having trouble with my checkbox question function - I want to limit the number of checkboxes that can be checked to 3, but it's still allowing more than that. I suspect the issue lies with latestcheck.checked = false; This is my typescript function: ...

Tips for tidying up duplicated typescript content sourced from a pre-existing library

Seeking guidance on implementing best practices and gaining a better understanding of my approach. After discovering the library react-google-calendar-api, I successfully installed it using npm in my React project. However, I wanted to expand its function ...

Ava tests hitting a snag with TypeScript ("Oops! Unexpected identifier found")

Currently delving into the realms of TypeScript, I decided to venture into creating a TypeScript React application using create-react-app. This application involves a separate TypeScript file called logic.ts, which in turn imports a JSON file. import past ...

When attempting to send a fetch request in the most recent rendition of NextJS, it ends up with an error of 'failed fetch'

I am currently working on a nextjs (v.13.4.19) / strapi (v.4.12.5) application and facing issues when trying to make a request to the strapi endpoint using the fetch function. I have attempted several troubleshooting steps such as: changing localhost:1337 ...

What could be causing the module version discrepancy with the package.json file I created?

Recently, I created a project using create-next-app and decided to downgrade my Next.js version to 12. After that, I proceeded to install some necessary modules using Yarn and specified the versions for TypeScript, React, and others. During this setup, I b ...

Accessing router params in Angular2 from outside the router-outlet

I am currently working on a dashboard application that includes a treeview component listing various content nodes, along with a dashboard-edit component that displays editable content based on the selected branch of the tree. For example, the tree struct ...

Tips for embedding Apache Superset visualizations into an Angular 7 app: Overcoming hurdles with authentication and headers

I am currently working with Apache Superset to create charts. I am looking to embed these charts in my Angular 7 application using an iframe. One major problem I encountered is an authentication failure with the following error message: Refused to display ...

Error in React Native Typescript: The type 'string' cannot be assigned to the type '"solid" | "clear" | "outline"'. (Error code: ts(2322))

I have integrated TypeScript with React Native in my project. import React from 'react'; import { Button } from 'react-native-elements'; import { IThemedButton } from '../../../models/themedButton'; interface IThemedButtonPr ...

Declaring global types in a NX and NextJS monorepository for enhanced development consistency

I've been searching online to find a good solution for my issue, but so far I haven't had any luck. Currently, I have a NX monorepo with NextJS and I'm attempting to create a global types/ folder that can be accessed by all my apps and libs ...

Ways to navigate to a routerlink in Angular 2 without passing any parameters

Struggling with accessing a routerlink in Angular 2 without its parameters. The goal is to use the routerlinks to determine whether or not to display a specific element in the navigation. For normal routerlinks without parameters, I do it like this: *ngIf ...

Guide to utilizing @types/node in a Node.js application

Currently, I am using VSCode on Ubuntu 16.04 for my project. The node project was set up with the following commands: npm init tsc --init Within this project, a new file named index.ts has been created. The intention is to utilize fs and readline to read ...

I am experiencing issues with the customsort function when trying to sort a column of

Seeking assistance with customizing the sorting function for a Date column in a primeng table. Currently, the column is displaying data formatted as 'hh:mm a' and not sorting correctly (e.g. sorting as 1am, 1pm, 10am, 10pm instead of in chronolog ...

Develop a desktop application using the Command Prompt in Windows with the .NET Core and Windows Form technologies

Looking for guidance on creating a .NET Core Desktop app using the Command Prompt? I attempted the process without success. dotnet new desktop -n Toha.CodeGenDesktopdotnet new desktop -n CodeGenDesktop I have also checked here but couldn't locate ...