Challenges arise when dealing with generics in TypeScript

I'm a beginner in TypeScript and I'm trying to write a method with a generic type argument similar to what you can do in .Net.

Here's the code snippet I've been working on:

class TestObject {
  Id: number;
  Truc: string;
  Machin: string;
}

export default
  {

    async FirstMethod(): Promise<TestObject> {
      return await this.TestMethodGen<TestObject>();
    },

    async TestMethodGen<T>(): Promise<T>  {
      // Json Deserialization other etc ...
      return <T>new Object();
    }
  }

However, I keep running into a TypeScript error TS2347 and I'm unsure of how to fix it.

TS2347 (TS) Untyped function calls may not accept type arguments.

https://i.sstatic.net/sYtwk.png

Thank you in advance for any assistance.

Answer №1

As stated in the TypeScript documentation.

When working with generics to create factories in TypeScript, it is important to reference class types using their constructor functions.

The code snippet below has been successfully tested on my system.

class TestObject {
    Id: number;
    Truc: string;
    Machin: string;
}

export default {
    async FirstMethod(): Promise<TestObject> {
        return await this.TestMethodGen(TestObject);
    },

    async TestMethodGen<T>(c: { new (): T }): Promise<T> {
        // Perform Json Deserialization and other operations ...
        return new c();
    }
};

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

Starting up a pre-existing Angular project on your local machine

I am completely new to Angular and facing difficulties running an existing project on my machine. Despite conducting numerous tests and following various articles, I still cannot get the project to run. Here is the layout of my project files: https://i.s ...

Having difficulty running lint on Vue 3 TypeScript application, but building process is successful

We are encountering an issue at the moment. We can successfully build our app, but we are facing challenges with linting using the vue tools (vue-cli-service ...). The hot-reloading feature works initially, but upon saving a file, we receive an error mess ...

The Power of TypeScript's Union Types

Provided: Reducer only accepts one of the following actions: interface ItemAction { type: 'ADD_TODO'|'DELETE_TODO'|'TOGGLE_TODO', id: number } interface QueryAction { type: 'SET_QUERY', query: string ...

The Action-Reducer Mapping feature is encountering a type error when handling multiple types of actions

Earlier today, I posed a question about creating a mapping between redux action types and reducers to handle each type explicitly. After receiving helpful guidance on how to create the mapping, I encountered an error when attempting to use it in creating ...

Error: The Class 'Subject<T>' does not properly extend the base class 'Observable<T>'

I encountered an error that says: **Build:Class 'Subject<T>' incorrectly extends base class 'Observable<T>** . I have TypeScript 2.4.1 installed and obtained angular quick starter files from the GitHub repository angular quick ...

Proceed the flow of event propagation using the react-aria button element

In the react-aria library, event bubbling for buttons is disabled. I am facing an issue where my button, which is nested inside a div that acts as a file uploader, does not trigger the file explorer when clicked due to event bubbling being disabled. How ...

What is the best way to access the original observed node using MutationObserver when the subtree option is set to

Is there a way to access the original target node when using MutationObserver with options set to childList: true and subtree: true? According to the documentation on MDN, the target node changes to the mutated node during callbacks, but I want to always ...

I am experiencing difficulties with TypeORM connecting to my Postgres database

Currently, I am utilizing Express, Postgres, and TypeORM for a small-scale website development project. However, I am encountering challenges when it comes to establishing a connection between TypeORM and my Postgres database. index.ts ( async ()=>{ ...

Enhancing a prototype instance in TypeScript while activating strict mode

When working with an instance named remote from a factory in a vendor script, I encountered the need to add my own methods and members to that instance. While seeking a solution, I came across an insightful response on extending this in a Typescript class ...

The issue with calling a public method from an onchange event triggered by a custom Google Maps control in the Ionic framework has been encountered

Hello, fellow developers! I am relatively new to Ionic and web programming in general. Currently, I am working on a small app that involves integrating the Google Maps JS API. While I have successfully created and loaded the map, as well as added a custom ...

Creating a dynamic path to an imported file in React: A step-by-step guide

Struggling with a dilemma regarding dynamically generated paths for importing files in React. I have utilized the map() function to generate a dynamic part of the code, consisting of a repetitive sequence of div elements, each housing an audio element. The ...

Using *ngFor to dynamically update the DOM when an array is modified via ngrx

Currently, I am utilizing *ngFor to present values from an array: [ { id: 1, name: 'item1' }, { id: 2, name: 'item2' } ] In the html: <div *ngFor="let item of (items$ | async); trackBy: trackById;&quo ...

What is the reason for the lack of variable assignment within the forEach method in Angular?

I am struggling with assigning a value to the variable "this.qdDias" and returning it. After using subscribe, I am unable to retrieve the value at the end of the method. Despite seeing the value in the console.log(this.qdDias), it becomes undefined when re ...

Seeking a quick conversion method for transforming x or x[] into x[] in a single line of code

Is there a concise TypeScript one-liner that can replace the arrayOrMemberToArray function below? function arrayOrMemberToArray<T>(input: T | T[]): T[] { if(Arrary.isArray(input)) return input return [input] } Trying to cram this logic into a te ...

Hiding columns in TanStack Ver 8: A step-by-step guide

Can someone assist me with dynamically hiding specific columns in Tanstack table ver 8? I have a column defined as follows: { header: "Case Number", accessorKey: "caseNumber", visible: false, // using this value ...

Tips for properly importing types from external dependencies in TypeScript

I am facing an issue with handling types in my project. The structure is such that I have packageA -> packageB-v1 -> packageC-v1, and I need to utilize a type declared in packageC-v1 within packageA. All the packages are custom-made TypeScript packa ...

I'm looking for a way to merge the functionalities of tsc build watch and nodemon into a single Node.js

Currently, I have two scripts in my code: "scripts": { "build": "tsc -p . -w", "watchjs": "nodemon dist/index.js" } I need to run these two scripts simultaneously with one command so that the build ...

What is the specific category of Mongoose.startSession in the realm of Typescript?

In my Express/Typescript project with mongoose, I implemented a loader as follows: import mongoose from 'mongoose'; import { Db } from 'mongodb'; import config from '../config'; export default async (): Pr ...

Updating a component in Angular 4.3.1 from within an observable callback

My Project Journey I am currently immersing myself in learning Angular by working on a personal project: developing a game that involves routing, services, and more. One of the requirements is to hide the header on the landing page (route for '/&apos ...

What is the process for setting a Type to a prop in React?

I have a main component: // DashboardComponent.tsx const DashboardComponent = () => { const {loading, error, data} = useQuery(resolvers.ReturnAllMovies); if (loading) return <p>loading</p>; if (error) return <p>Error! ${error.m ...