Using the appropriate parameters is key: TS2345: The argument of type 'T' cannot be assigned to a parameter of type 'new() => any'

Struggling with Typescript 2, I am attempting to create a universal parser-method for database objects. Utilizing TypedJSON, I am encountering difficulties in correctly organizing the parameters. Here is part of my code:

private static parseToInstance<T>(dbObject: string, model: T): T {
    try {
        console.log("parseToInstance()")
        let a = TypedJSON.stringify(dbObject);
        return TypedJSON.parse(a, new model, "whatever"
    } catch (err) {
        throw new ParseException(err);
    }
}

The method should receive input similar to:

/**
* Converts a JavaScript Object Notation (JSON) string into an instance of the provided class.
* @param text A valid JSON string.
* @param type A class from which an instance is created using the provided JSON string.
* @param settings Per-use serializer settings. Unspecified keys are assigned from global config.
*/
parse<T>(text: string, type: {new (): T;}, settings?: SerializerSettings): T;

An error I am encountering in my code is:

Error:(125, 30) TS2345:Argument of type 'T' is not assignable to parameter of type 'new () => {}'.

Despite attempting multiple solutions, I am unable to resolve this issue. Any assistance would be greatly appreciated.

Answer №1

By utilizing the {new (): T;} type annotation, you are signaling the presence of a constructor.

In order to accommodate this, adjustments need to be made in your parseToInstance function. Instead of simply model: T, it is necessary to specify the type as {new():T} to clearly identify it as a constructor. TypeScript's generics differ from other languages in that they do not always define classes explicitly, hence the need for this specificity. Additionally, avoid calling new on the model before passing it into the function, as this would defeat the purpose of utilizing a constructor function.

private static parseToInstance<T>(dbObject: string, model: {new():T}): T {
    try {
        console.log("parseToInstance()")
        let a = TypedJSON.stringify(dbObject);
        return TypedJSON.parse(a, model, "whatever");
    } catch (err) {
        throw new ParseException(err);
    }
}

p.s. There was a missing closing parenthesis in "parse," which has been rectified.

Answer №2

Consider something along the lines of:

public static deserialize<T>(data: string, type: { new(): T }): T {
    ...
    return TypedJSON.parse(data, type, "custom");
}

There are two important modifications:

  1. Use { new(): T } instead of just T
  2. Pass the type instead of creating a new instance

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

Setting up shortcuts for webpack using lerna and typescript

I have set up a repository to showcase an issue I am facing: https://github.com/vileen/lerna-webpack-typescript-aliases-issue (the app does not start properly, but that's not the main concern). The main question here is how can I enhance importing fr ...

a helpful utility type for extracting a union from a constant array of strings

I create string arrays using const assertions and then use them to generate union types. const elements = ["apple", "banana", "orange"] as const; type elementsUnion = typeof elements[number]; // type elementsUnion = "appl ...

Identified the category

How can I retrieve the default option from a list of options? type export type Unpacked<T> = T extends Array<infer U> ? U : T; interface getDefaultValue?: <T extends Option[]>(options: T) => Unpacked<T>; Example const options = ...

Tips for handling delayed HTTP API responses in Angular

While working on my project, I encountered a delay in response when using the this.ServiceHandler.getTxnInfo([], params) API. To handle this, I implemented the use of setTimeout along with async/await. Despite these modifications, my promise ended up being ...

Vue: Storing selected list values in an array

I am working on a Vue application where I need to select two elements from a list component and place them inside an array. Currently, I have my list set up with selection functionality thanks to Vuetify. I have bound the selected items to an array using v ...

What is the TypeScript's alternative to ReasonML's option type?

When using ReasonML, the option type is a variant that can be either Some('a) or None. If I were to represent the same concept in TypeScript, how would I go about it? ...

`Developing reusable TypeScript code for both Node.js and Vue.js`

I'm struggling to figure out the solution for my current setup. Here are the details: Node.js 16.1.x Vue.js 3.x TypeScript 4.2.4 This is how my directory structure looks: Root (Node.js server) shared MySharedFile.ts ui (Vue.js code) MySharedFi ...

Guide to setting the order of rendering in React applications

I am currently working with a .tsx file that renders two components: export default observer(function MyModule(props: MyModuleProps) { .... return ( <div> <TopPart></TopPart> <LowerPart>< ...

Passing RxJs pipes as a parameter

Is there a way to pass pipes as parameters? For example: var mypipes = [ pipeA(() => { alert("a"); }), pipeB(() => { alert("b"); }) ...

Typescript enhances the functionality of the Express Request body

I need help with the following code snippet: const fff = async (req: express.Request, res: express.Response): Promise<void> => {...} How can I specify that req.body.xxx exists? I want it to be recognized when I reference req.body.xxx as a propert ...

Creating a unique custom selector with TypeScript that supports both Nodelist and Element types

I am looking to create a custom find selector instead of relying on standard javascript querySelector tags. To achieve this, I have extended the Element type with my own function called addClass(). However, I encountered an issue where querySelectorAll ret ...

I was able to use the formGroup without any issues before, but now I'm encountering an error

<div class="col-md-4"> <form [formGroup]="uploadForm" (ngSubmit)="onSubmit(uploadForm.organization)"> <fieldset class="form-group"> <label class="control-label" for="email"> <h6 class="text-s ...

Eliminate properties from a TypeScript interface object

After receiving a JSON response and storing it in MongoDB, I noticed that unnecessary fields are also being stored in the database. Is there a way to remove these unnecessary fields? interface Test{ name:string }; const temp :Test = JSON.parse('{ ...

I'm curious about the origins of the "readme" field within the artifact registry file

Within our private npm registry on Azure, we house our own npm package alongside the npmjs packages. One particular package, @typescript-eslint/parser, has caused our pipelines to fail during the npm install task due to a SyntaxError: Unexpected end of JSO ...

What types should be used when passing a NgRx Action as a parameter to a function?

Within my Effects function, I have implemented the following code structure. I have included a few lines of code for the catchError block to ensure that: Any errors are handled by the state/store The errors are forwarded to the global error handler / Int ...

The module 'three/examples/jsm/controls/OrbitControls' or its corresponding type declarations could not be located

In my React project, I am utilizing TypeScript and three.js, where I'm importing OrbitControls in the following manner: import * as THREE from "three"; import { OrbitControls } from "three/examples/jsm/controls/OrbitControls"; How ...

Ways to utilize a field from an interface as a type of index

interface Mapping { "alpha": (a: string) => void "beta": (b: number) => void } interface In<T extends keyof Mapping> { readonly type: T, method: Mapping[T] } const inHandlers: In<"alpha"> = { type ...

Encountering error TS2307 while using gulp-typescript with requirejs and configuring multiple path aliases and packages

Currently, I am working on a substantial project that heavily relies on JavaScript. To enhance its functionality, I am considering incorporating TypeScript into the codebase. While things are running smoothly for the most part, I have encountered an issue ...

What is the abbreviation for a 'nested' type within a class in TypeScript?

Consider the TypeScript module below: namespace AnotherVeryLongNamespace { export type SomeTypeUsedLater = (a: string, b: number) => Promise<Array<boolean>>; export type SomeOtherTypeUsedLater = { c: SomeTypeUsedLater, d: number }; } cl ...

The received data object appears to be currently undefined

I am currently using MapBox to display multiple coordinates on a map, but I am encountering an issue where the longitude and latitude values in my return object are showing up as undefined. Could there be a missing configuration that is preventing the data ...