Creating Instances of Parameterized Types

Consider the following scenario:

class Datum {}

An error message (

error TS2304: Cannot find name 'T'
) is encountered when attempting the following:

class Data<T extends Datum> {
    datum: T

    constructor() {
        this.datum = new T()
    }
}

Subsequently, an attempt is made which results in another error message (

Type 'Datum' is not assignable to type 'T'
):

 class Data<T extends Datum> {
    datum: T

    constructor() {
        this.datum = new Datum();
    }
}

Query: Is it impossible to create instances of the constrained types like T? The expectation was that since T is restricted to extend Datum, assigning datum: T = new Datum() should be feasible.

Answer №1

Don't forget two important things: First off, generics are completely removed during compilation. They don't have any impact at runtime, so trying to treat a generic type as if it were a runtime value is pointless.

Secondly, it's worth noting that a subclass of Datum may have constructor parameters. Even if T actually existed, you can't just blindly call new on it with no arguments.

Putting it all together, what you need is something like this:

class Datum {}

class Data<T extends Datum> {
    datum: T

    constructor(ctor: new() => T) {
        this.datum = new ctor();
    }
}

class ByteDatum extends Datum {
    new() { }
}

let y = new Data(ByteDatum);
let x = y.datum; // x: ByteDatum

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

The functionality of verifying the type of an item in a list using Typescript is not functioning

In my TypeScript code, I am working with a type called NameValue and another one called MixedStuff. type NameValue = { name: string; value: string }; type MixedStuff = NameValue | string; function stripTwoChars(stuffs: MixedStuff[]): string { let st ...

Angular 5: Issues with retrieving response using HttpClient's get request

Alright, so typically I work with Angular 1.*, but I decided to dive into Angular 5 and man, it's been a bit of a challenge. It feels unnecessarily complex, but oh well... So I'm trying to make an HTTP call, and I have this node API that is retu ...

Speedy Typescript inquiry query

I'm currently in the process of creating a basic endpoint by following the Fastify with Typescript documentation linked below: https://www.fastify.io/docs/v3.1.x/TypeScript/ export default async function customEndpoint(fastify: any) { const My ...

What is the best way to display a Nested JSON structure without an object key?

Need help with extracting data from two different JSON structures. The first one is straightforward, but the second is nested in multiple arrays. How can I access the content? See below for the code snippets: // First JSON { "allSuSa": [ { ...

Having difficulty importing the WebRTCAdaptor from the antmedia package stored in the node modules directory into an Angular Typescript file

An error is appearing indicating that: There seems to be a problem finding a declaration file for the module '@antmedia/webrtc_adaptor/js/webrtc_adaptor.js'. The file 'D:/web/node_modules/@antmedia/webrtc_adaptor/js/webrtc_adaptor.js' ...

What is the proper way to call document methods, like getElementByID, in a tsx file?

I am currently in the process of converting plain JavaScript files to TypeScript within a React application. However, I am facing an error with document when using methods like document.getElementById("login-username"). Can you guide me on how to referen ...

Send a collection of objects by submitting a form

I have a component with the following html code. I am attempting to dynamically generate a form based on the number of selected elements, which can range from 0 to N. <form #form="ngForm" id="formGroupExampleInput"> <div class="col-xs-5 col-md- ...

"Exploring Angular: A guide to scrolling to the bottom of a page with

I am trying to implement a scroll function that goes all the way to the bottom of a specific section within a div. I have attempted using scrollIntoView, but it only scrolls halfway down the page instead of to the designated section. .ts file @ViewChild(" ...

Angular2 error: "missing exported member 'bootstrap'"

Upon opening my Atom editor, I encountered the following message: The issue of 'Module '"C:/express4/node_modules/@angular/platform-browser-dynamic/index"' not exporting member 'bootstrap' raised at line 2 col 10 This warning a ...

The process of automatically formatting Typescript has transformed into an unfortunate auto-discarding action

Typescript autoformatting has become a concerning issue. Whenever I input quoted strings (" or `), the code surrounding it seems to temporarily glitch, with other strings appearing as code. This problem has recently escalated, particularly with strings li ...

Why do variables in an HTML file fail to update after being navigated within onAuthStateChanged?

Currently, I am working with Ionic 5 and Firebase. Everything is running smoothly until I implemented the onAuthStateChanged function to persist login for authenticated users. Here is the code snippet: this.ngFireAuth.onAuthStateChanged((user) => { ...

The element you are trying to access, "noUiSlider," does not belong to the type "HTMLElement" and cannot be found

Running into a roadblock here. What mistake am I making? .... /// <reference path="../../../typings/tsd.d.ts" /> var slider:HTMLElement = document.getElementById('slider'); noUiSlider.create(slider, { start: +$input.val(), step: + ...

Is there a way to dynamically adjust the size of mat dialog content to match the size of the mat dialog in

I have adjusted the size of my mat dialog, but the content is still stuck at the original size. To illustrate, here are some images: https://i.stack.imgur.com/2lLV2.jpg After researching, I found that it can be resized using CSS. I attempted the followin ...

Using AngularFire2 to manage your data services?

After diving into the resources provided by Angular.io and the Git Docs for AngularFire2, I decided to experiment with a more efficient approach. It seems that creating a service is recommended when working with the same data across different components in ...

What could be causing the TypeScript exhaustive switch check to malfunction?

How come the default case in the switch statement below does not result in an exhaustive check where 'item' is correctly identified as of type 'never'? enum Type { First, Second } interface ObjectWithType { type: Type; } c ...

Looking to update the state of a nested object with useReducer?

I am currently developing a Next.js application using Typescript and I need to make changes to a nested object state. Here is the structure of the state: const initialState ={ userInfo: string | null, isLoading: boolean, cursorState: boolean, compa ...

Creating a dynamic image binding feature in Angular 8

I am working with an object array that requires me to dynamically add an image icon based on the type of credit card. Typescript file icon: any; savedCreditCard = [ { cardExpiryDateFormat: "05/xx", cardNumberLast: "00xx", cardId: "x ...

The type 'Requireable<string>' cannot be matched with the type 'Validator<"horizontal" | "vertical" | undefined>'

code import * as React from 'react'; import * as PropTypes from 'prop-types'; interface ILayoutProps { dir?: 'horizontal' | 'vertical' }; const Layout: React.FunctionComponent<ILayoutProps> = (props) => ...

Deciphering intricate Type Script Type declarations

I am seeking clarification on how to utilize the object type for sending headers, aside from HttpHeaders provided in the HTTPClient declaration. While working with Angular HttpClient, I aim to include headers using an Object. However, I am unsure of how t ...

When evaluating code with eval, properties of undefined cannot be set, but the process works seamlessly without

Currently, I am attempting to utilize the eval() function to dynamically update a variable that must be accessed by path in the format myArray[0][0[1][0].... Strangely enough, when I try this approach, I encounter the following error: Uncaught TypeError: ...