Treating generics as a concrete value in TypeScript

Experimenting with generics in typescript led me to face a frustrating challenge with a perplexing error message from typescript.
My attempt to create a wrapper for generating classes with a common base class ended in encountering the following error message:

'T' only refers to a type, but is being used as a value here. ts(2693)

Below is the snippet of code where this issue arises:


class Test {
    constructor(i: number) {
        
    }
}

class Test1 extends Test {

}
class Test2 extends Test {

}

function f<T extends Test>(n:number): T {
    return new T(n)
}

Although the following code works, it lacks generality:

function f1(n: number): Test1 {
    return new Test1(n)
}

For further exploration, here's the typescript playground.

Can someone shed light on the confusion here and guide me on how to resolve it?
I also attempted creating an interface that specifies a mandatory CTOR, but it appears to be unsupported.

Answer №1

In JavaScript, generic types are not supported as they only define types and do not actually exist.

However, you can achieve similar functionality by passing your class as an argument, like so:

function f<T extends Test>(clss: new() => T, n:number): T {
    return new T(n)
}

By doing this, the type of the class will be inferred and you can call it as:

f(Test2, 2)

The result of the function call will be of type Test2

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

Looking to receive detailed compiler error messages along with full imports in Visual Studio Code for TypeScript?

Currently, I am trying to edit a piece of typescript code in Visual Studio Code. However, I encountered a compiler error message that looks like this: The error states: Type 'import(\"c:/path/to/project/node_modules/@com.m...' is not assign ...

An error has occurred in Typescript stating that there is no overload that matches the call for AnyStyledComponent since the update to nextjs

Upgraded to the latest version of nextjs, 13.3.1, and encountered an error in the IDE related to a styled component: Received error TS2769 after the upgrade: No overload matches this call. Overload 1 of 2, '(component: AnyStyledComponent): ThemedSty ...

Executing TypeScript Mocha test cases using ES6 modules

Setting up mocha tests for the TypeScript App in my Rails application has been a bit of a challenge. Initially, I added a basic test to kick things off, but encountered the following error: /home/bernhard/Programs/ruby/cube_trainer/jstests/utils/optional. ...

Can Angular 9 be used to compile a latex document?

Is it possible to utilize Angular 9 to compile and generate PDF files using latex? Specifically, I am curious about how to compile a document using Angular and Pdflatex. The idea is for the client to input their data in the form of a JSON data structure ...

The variable 'string' has been declared, but it is never utilized or accessed

Currently delving into Typescript and facing an early error. Despite following a tutorial, I'm encountering multiple errors that I have attempted to comment out. Would greatly appreciate it if someone could shed some light on why these errors are occu ...

The TypeScript error message is saying that it cannot find the property 'push' of an undefined value, resulting in a error within the

Issue: Unable to access property 'push' of undefined in [null]. class B implements OnInit { messageArr: string[]; ngOnInit() { for(let i=0; i<5; i++) { this.messageArr.push("bbb"); } } } ...

How can I transform this imperative reducer into a more declarative format using Ramda?

I am currently working with a reducer function that aggregates values in a specific way. The first argument is the aggregated value, while the second argument represents the next value. This function reduces over the same reaction argument, aggregating th ...

What is the proper syntax for defining an object property as a function?

Could someone help me find the specific location in the documentation where I can learn about the syntax of the line testMessage: (): string => {? Shouldn't it be more like testMessage: () => string;? Why are they not the same? export default { ...

Vercel - Deploying without the need to promote the project

How can I deploy my Nextjs app to production in a way that allows me to run E2E tests on a "pre-prod" version before promoting it to prod, similar to using a preview URL without public traffic being directed there? I am looking for a process where I can v ...

Exploring Angular 2 with Visual Studio 2015 Update 1 in the context of Type Script Configuration

After spending the last week attempting to set up and launch a simple project, I am using the following configuration: Angular 2, Visual Studio 2015 update 1, TypeScript Configuration In the root of my project, I have a tsconfig.Json file with the follow ...

Issue TS8011 in Angular 6 is related to the restriction on using type arguments only in files with the .ts extension

I have a project in Angular 6 where I need to integrate a JS library. This library is confidential, so I can't disclose its details. The problem I'm facing is that the TypeScript compiler seems to misinterpret characters like <<24>>, ...

Learning to handle data fetching and looping in NextJs

I'm facing an issue with fetching data through a loop in getStaticProps. The array ends up empty due to asynchronous code. If I pass the ID array and implement the logic within the React component, it works fine. Should I continue using the component ...

How can I ensure that all the text is always in lowercase in my Angular project?

Is there a way to ensure that when a user enters text into an input field to search for a chip, the text is always converted to lowercase before being processed? Currently, it seems possible for a user to create multiple chips with variations in capitaliza ...

Angular - Loading images on the fly

After scouring numerous resources, I couldn't find a resolution to my issue. For your information, I am utilizing ASP.net Core 2.0's default angular project In the process of developing an Angular application, I am faced with the challenge of ...

I seem to be stuck in an endless cycle with React hooks and I can't figure out the root cause

Explore the example here: https://codesandbox.io/s/wandering-wildflower-764w4 Essentially, my goal is to achieve the following: In the provided example, I have a server validation function that has been mocked. My objective is to maintain the state local ...

Tribal Code Typescript Compiler

Typescript is a great alternative to Javascript in my opinion, but it bothers me that it requires node.js as a dependency. Additionally, I find it frustrating that there seems to be only one compiler available for this language, and it's self-hosted. ...

Switch the MatSlideToggle within an Angular 8 component

I seem to be encountering a persistent error: "ERROR TypeError: Cannot set property 'checked' of undefined" Take a look at my code snippet from test.component.ts: import { Component, OnInit, ViewChild } from '@angular/core'; import { ...

Angular2- Retrieving configuration information during application launch

Implementing a method to load configuration data from an ASP.NET web API using HTTP at startup via APP_INITIALIZER. This approach was influenced by a discussion on Stack Overflow about loading configuration in Angular2 here and here. Snippet from app.modu ...

Creating a User-friendly Layout for Admin Pages in Next.js Version 13

Hey there, I'm facing an issue with the layout while using Next.js 13 Experimental App Directory. On my website's index page or routes '/', I want to show a landing page and use a specific layout for all pages except for those under the ...

Increasing the token size in the Metaplex Auction House CLI for selling items

Utilizing the Metaplex Auction House CLI (ah-cli) latest version (commit 472973f2437ecd9cd0e730254ecdbd1e8fbbd953 from May 27 12:54:11 2022) has posed a limitation where it only allows the use of --token-size 1 and does not permit the creation of auction s ...