What is causing the error TS2339 to be thrown when attempting to access a class property in this TypeScript illustration: "Property 'text' does not exist on type 'T'"?

Could someone provide insight into why attempting to access a class property in this scenario is resulting in the error message

error TS2339: Property 'text' does not exist on type 'T'.

Here is the TypeScript code:

class Base {
    readonly name: string = this.constructor.name;
};

class MyClass extends Base {
    text: string;

    constructor(v: string) {
        super();
        this.text = v;
    }
};

function CreateMyClass<T>(type: new (v: string) => T) {
    console.debug('CreateMyClass: type:', type)

    const myClass: T = new type('hello world');

    console.debug('CreateMyClass: myClass:', myClass);
    // console.debug('CreateMyClass: myClass.text:', myClass.text);
}

CreateMyClass(MyClass);

The output is as follows:

CreateMyClass: type: [class MyClass extends Base]
CreateMyClass: myClass: MyClass { name: 'MyClass', text: 'hello world' }

If we uncomment the last console.debug statement, the output displays the error:

test/index.ts:20:59 - error TS2339: Property 'text' does not exist on type 'T'.

20     console.debug('CreateMyClass: myClass.text:', myClass.text);
                                                             ~~~~

Answer №1

Both @CodingGenius and @programmingpro provided insights on my initial query. It was confirmed by @CodingGenius that my question was actually an example of the "XY Problem".

SOLUTION: "...You're encountering an issue where the TS type is not stored as it only exists during compile time. It's important to note that the type 'T' may not necessarily contain text, as illustrated in my previous comment." – @CodingGenius

As for my primary concern, "Is it possible to modify a property instantiated by the function CreateMyClass?" - The answer is no.

I previously mentioned my quest for a resolution to a different issue:

The challenge of retrieving an element of type T (where T is a subclass of BaseClass) from an array of objects of the class BaseClass, using a function that takes the derived class as input. The following code snippet exemplifies this:

class Base {
    readonly name: string = this.constructor.name;
};

class MyClass extends Base {
    text: string;

    constructor(val: string) {
        super();
        this.text = val;
    }
};

class MyContainer {
    arr: Base[] = [];

    getChild<T>(childType: new (s: string) => T): T {
        for (const child of this.arr) {
            if (child instanceof childType) {
                return child;
            }
        }

        return undefined;
    }
}

const myContainer: MyContainer = new MyContainer();
myContainer.arr.push(new MyClass('some value'));

console.debug(myContainer.getChild(MyClass));

Output of console.debug:

MyClass { text: "some value" }

In the end, I managed to find a solution to the core problem. I hope this serves as a useful guide for others delving into TypeScript.

A big thank you to @CodingGenius and @programmingpro for their valuable assistance.

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

Typescript integration with Sequelize CLI for efficient database migrations

According to the Sequelize documentation, it claims to work with Typescript. However, for it to be fully functional in a production environment, DB migration scripts are necessary. The issue arises when using the Sequelize CLI as it only generates and runs ...

Leveraging Typescript's robust type system to develop highly specific filter functions

I'm attempting to utilize the robust TypeScript type system in order to construct a highly typed 'filter' function that works on a collection (not just a simple array). Below is an illustration of what I am striving for: type ClassNames = &a ...

Having trouble utilizing a JavaScript file within TypeScript

I am currently exploring the integration of Three.js into an Angular application. Following the documentation, I imported Three.js using the following line: import * as THREE from 'three'; In addition, I installed the types for Three.js with th ...

Is it possible to obtain Literal types for object keys dynamically in typescript?

I am looking to extract the type of object keys. Below is a generic function for objects with keys as strings: type GenericInput = { [key:string]: {value:string,type:HTMLInputTypeAttribute,placeholder:string,min?:number,max?:number,required?:boolean, err ...

Is it possible to set up TypeScript npm packages to be installed in their original TypeScript format rather than JavaScript for the purpose of examining the source code?

Despite my lack of expertise in the inner workings of how a TypeScript library compiles itself to JavaScript before being placed in the node_modules directory, I have a question: Coming from a PHP background, I am accustomed to being able to explore any l ...

What is the reason behind decorators needing to utilize apply(this) on a function?

I've been delving into the realm of JavaScript and exploring decorator code. One thing I've noticed is that when looking at decorator code like the example below, the input function always applies to 'this' even though it doesn't a ...

Navigating the interface types between Angular, Firebase, and Typescript can be tricky, especially when working with the `firebase.firestore.FieldValue`

I am working on an interface that utilizes Firestore timestamps for date settings. export interface Album{ album_name: string, album_date: firebase.firestore.FieldValue; } Adding a new item functions perfectly: this.album ...

Assigning the output of a function to an Angular2 component (written in TypeScript)

I have a small utility that receives notifications from a web socket. Whenever the fillThemSomehow() method is called, it fetches and stores them in an array. @Injectable() export class WebsocketNotificationHandler { notifications: Array<Notificati ...

What is the best way to extract values from a specific table column and store them in an array using Angular?

I have a section of code containing a table in my component: expect-next-month.component.html <table id="users"> <tr> <th>Number of month</th> <th>Total checking e ...

What is the best way to first identify and listen for changes in a form

In Angular, there are reactive forms that allow you to track changes in both the complete form and specific fields: this.filterForm.valueChanges.subscribe(() => { }); this.filterForm.controls["name"].valueChanges.subscribe(selectedValue => { }); ...

"Utilizing Typescript and React to set a property's value based on another prop: A step-by

Is there a way to create a dynamic prop type in React? I have an Alert component with various actions, such as clicking on different components like Button or Link. I am looking for a solution like this: <Alert actions={[{ component: Link, props: { /* ...

Angular Error: Attempting to access property 'then' of undefined object causes TypeError

I am struggling with implementing JHipster Auth-guard. I am facing an issue where canActivate is not triggered for a user without permission for a specific route. I have carefully examined my code, but the console shows that .then() is undefined at the sp ...

Sharing information between components in Angular through service communication

In my Angular 4 project, there is a functionality where upon clicking on one of the 'groups', its tile should be added to a list of 'favourites' which is represented as an array. To implement this feature, I utilized a BehaviorSubject. ...

I am curious if there exists a VSCode plugin or IDE that has the ability to show the dependencies of TypeScript functions or provide a visual representation

Are there any VSCode plugins or IDEs available that can display the dependency of TypeScript functions or show a call stack view? I am looking for a way to visualize the call stack view of TypeScript functions. Is there a tool that can help with this? Fo ...

Executing installed packages using npm: A step-by-step guide

Recently, I have encountered a confusing issue in my coding journey. In Python, I got used to installing packages and using them right away without any hiccups. For example, with SpotDL, everything worked seamlessly. However, things took a different turn w ...

Having trouble with the removeEventListener OnDestroy not functioning properly in Angular 6 using Javascript?

I have been experimenting with using the removeEventListener function in my Angular component. I came across a helpful discussion on this topic: Javascript removeEventListener not working ... ngOnInit() { document.addEventListener('v ...

The TypeScript Type inside the Node Module Doesn't Seem to Be Functioning

In my React project, I am using the material-ui@next library along with typescript. Below is the code snippet that I have written: <CardMedia image={item.image_url} style={{ width: 238, height: 124.5 }} /> However, when I try to compile this code, ...

Retrieving an array of objects from an API and attempting to store it using useState, but only receiving an empty

I have been working on fetching data from an API, storing it in Redux store initially, and then attempting to retrieve it using useSlector to finally save it in local state. Despite getting the data when I console.log it, I am unable to successfully store ...

Implementing an interface with a variable key and defining the key simultaneously

I am trying to design an interface with a fixed key, as well as a variable key, like this : interface Data { api?: { isReady: boolean; }; [key: string]: string; } This setup gives me the following error message : Property 'api' of typ ...

Is there a way to get this reducer function to work within a TypeScript class?

For the first advent of code challenge this year, I decided to experiment with reducers. The following code worked perfectly: export default class CalorieCounter { public static calculateMaxInventoryValue(elfInventories: number[][]): number { const s ...