Inference of generic types within a TypeScript generic

In my coding journey, I came across a situation where I was dealing with generic classes. Specifically, I had a Generic class Generic<T> and another one called GenericWrap that used Generic as its maximum type parameter (denoted as U extends Generic<any>). Inside GenericWrap, there is a member named generic, which is an instance of Generic using any as the value type.

In an attempt to extend the functionality further, I created NumberGenericWrap by extending GenericWrap with a type parameter <NumberGeneric>. My goal was to set the type of NumberGenericWrap.generic to be Generic<number>, allowing the result of NumberGenericWrap.getValue() to be of type number. However, when testing it out, I noticed that the return type ended up being 'any' instead.

This made me wonder - does TypeScript actually support what I am trying to achieve here?

class Generic<T> {
    val: T;
}

class NumberGeneric extends Generic<number> {

}

class GenericWrap<U extends Generic<any>> {

    generic: U;

    getValue() {
        return this.generic.val;
    }
}

class NumberGenericWrap extends GenericWrap<NumberGeneric> {

}

let n = new NumberGenericWrap();

// expected 'typeof val' => number 
// actual 'typeof val' => any
let val = n.getValue();

Answer №1

The reason why the type checker is not attempting to infer the val type remains unclear, but there is a workaround available. All you need to do is explicitly instruct the type checker to look up the generic type and determine the val type.

type ValType<T extends Generic<any>> = T["val"];

class GenericWrap<U extends Generic<any>> {

    generic: U;

    getValue(): ValType<U> {
        return this.generic.val;
    }
}

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

Arranging strings in descending order using Typescript

I was attempting to arrange a string[] in a descending order. This is what I have come up with so far: let values = ["Saab", "Volvo", "BMW"]; // example values.sort(); values.reverse(); Although this method is effective, I am wondering if there is a mo ...

Setting up Webhook for Clerk in a Next.js and Prisma (T3 stack) environment

I am facing a challenge in my personal project using Next.js (T3 stack) where I need to synchronize Clerk users with a user table in my Supabase DB. My goal is to have a Users table, defined in my schema.prisma, that includes the user_id from Clerk along ...

Defining a type with limited knowledge: if you only have one key in the object

Attempting to establish a type for an object Consider the following object structure: { a: 123, b: "hello", c: { d:"world" } } The keys present in the object are unknown. To define its type, I would use Record<st ...

Steps for creating a dynamic validation using a new form control

I have an item that needs to generate a form const textBox = { fontColor: 'blue', fontSize: '18', placeholder: 'email', name: 'input email', label: 'john', validation: { required: false } ...

How long does it take to delete and recreate a cloudfront distribution using AWS CDK?

I am currently undergoing the process of migrating from the AWS CDK CloudfrontWebDistribution construct to the Distribution Construct. According to the documentation, the CDK will delete and recreate the distribution. I am curious about the total duration ...

What could be the reason for the ERROR message saying, "Cannot read property '0' of undefined"?

I'm really struggling to understand why I keep receiving an Undefined error for tagged_Assets. Can someone please shed some light on this for me? Thank you. Model.ts export class TaggedAssests { device_id: string; hasTag: boolean; } Compon ...

Navigating Between Pages with Parameters in Ionic 2 (starter app)

I have an Ionic 2 project with a blank template containing a page that displays a list. Upon clicking on an item in the list, the user should be able to view more details about that specific item. Below are the files related to the list: list.html: <i ...

Addressing the reactivity issue when incorporating basic markdown directive into vuejs

In an effort to reduce dependency on vue-i18n formatting, I decided to create a simple Markdown formatter directive that only implements bold, emphasize, and strike-through styles. The current implementation of the directive is as follows: import _Vue ...

Why does my array seem to update only once in the view?

I am currently working on a project that aims to visually represent sorting algorithms, but I have encountered an issue. In order to effectively visualize the sorting process of an algorithm, it is crucial to display every change in the array as the proc ...

Creating sophisticated TypeScript AngularJS directive

Recently, I came across a directive for selecting objects from checkboxes which can be found at this link: The issue I'm facing is that we are using TypeScript and I am unsure of how to implement the directive in TypeScript. From what I understand, ...

Using Typescript in the browser with Babel and Webpack: Step-by-Step Guide

I've been exploring the use of Typescript in my browser with a specific architecture: Typescript in browser architecture However, I'm facing an issue with the import/export functionality when running this command: tsc && babel build-ts -d lib && ...

While the AWS CodePipeline is executing the script, an error is appearing in the log. Please address this issue and resolve it

This is the content of buildspec.yml: version: 0.2 phases: install: commands: - npm install -g typescript pre_build: commands: - echo Installing source NPM dependencies... - npm install build: commands: - echo Bui ...

Tips on revealing TypeScript modules in a NodeJS environment

Currently, I am working on developing a TypeScript library. My goal is to make this library compatible with both TypeScript and JavaScript Node projects. What would be the most effective approach for achieving this? Should I create two separate versions ...

Angular 8 ngFor not displaying expected information from object

I have a set of data which includes IDs, versions, and user details for Paul and Peter. See below: var data = { id: 1 version: 1 user: [ { name: 'paul' }, { name: 'peter' ...

TypeORM ensures that sensitive information, such as passwords, is never returned from the database when retrieving a user

I developed a REST API using NestJs and TypeORM, focusing on my user entity: @Entity('User') export class User extends BaseEntity { @PrimaryGeneratedColumn() public id: number; @Column({ unique: true }) public username: string; publi ...

Problem with dynamic page routes in Next.js (and using TypeScript)

Hi everyone, I'm currently learning next.js and I'm facing an issue while trying to set up a route like **pages/perfil/[name]** The problem I'm encountering is that the data fetched from an API call for this page is based on an id, but I wa ...

Supplier for a module relying on data received from the server

My current component relies on "MAT_DATE_FORMATS", but I am encountering an issue where the "useValue" needs to be retrieved from the server. Is there a way to make the provider asynchronous in this case? export const MY_FORMATS = { parse: { d ...

Exploring the concept of inheritance and nested views within AngularJS

I've encountered a challenge while setting up nested views in AngularJS. Utilizing the ui-router library has been beneficial, but I'm facing issues with separate controllers for each view without proper inheritance between them. This results in h ...

Is Aurelia-Fetch reliant on whatwg-fetch as a dependency in its codebase?

I am currently in the process of updating my Aurelia project from a beta version to the March version. One of the issues I encountered is: Cannot locate name 'Request'. Searching online led me to this problem on GitHub: https://github.com/au ...

Guide on combining vendor CSS files in a React application using Webpack

Incorporating third-party libraries is an essential part of my project. For example, I have Mapbox GL installed via npm, which comes with CSS files needed for its functionality. The Mapbox GL CSS file can be found at mapbox-gl/dist/mapbox-gl.css in the no ...