What causes TypeScript to fail in inferring the types of function parameters?

class Base<T> {
    public state = {} as T;
    public getState(): T {
        return this.state
    }
    public setState(v: T) {
        this.state = v
    }
}

interface DogProps {
    name: 'hello';
    age: 123;
}

class Dog extends Base<DogProps> {
    public sayName() {
        console.log('name: ', this.state.name);
    }
    public sayAge() {
        console.log('age: ', this.state.age);
    }
}

function test<U, T extends Base<U>>(Cor: new () => T): [U, T] {
    const dog = new Cor();
    const state = dog.getState();
    return [state, dog];
}

const [state1, dog1] = test(Dog); // state1 is unknow

const [state2, dog2] = test<DogProps, Dog>(Dog); // verbose but right

demo playground

I am newbe in typescript.
I thought the code I wrote was correct. However, it does not behave as expected.
Why is the type of state1 unknown?
Is there a way to determine the correct type without using test<DogProps, Dog>(Dog)?

Many thanks!!!

Answer №1

This particular issue arises due to the way generic resolution functions in Typescript. When T is referenced in the arguments, Typescript attempts to resolve it. However, since the constraint is based on U, it tries to resolve U first. Since U does not appear anywhere in the argument list, it remains unresolved and defaults to unknown.

To resolve this, make sure that U is included in the argument list. This way, Typescript will be able to resolve it without needing to determine T first:

function test<U, T extends Base<U>>(Cor: new()=>(T & Base<U>)): [U, T] {
                                                 // ^here^
}

Implementing this adjustment should solve the problem :)

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

Is there a way to seamlessly transition between different Angular components without having to refresh the entire webpage?

I'm currently working on implementing a navigation bar that allows users to switch between three components without having the navbar reload. The goal is for only the new component to load when the user clicks on a different section of the navbar, kee ...

The customized theme for Material UI version 5.10.9 is reflected in the Box component

, As of late, I've been utilizing Material UI version 5 in React. When creating a custom theme and incorporating my own palette, I observed that the Box component adheres to the default Material UI theme and disregards my customized theme. Curiously, ...

What is the reason for the absence of a PasteEvent type in the types/jquery library?

Why doesn't jQuery have a specific type for PasteEvent or ClipboardEvent? While there is a standard type for paste events (ClipboardEvent), jQuery does not have a specific event type for it. view image description here view image description here I ...

What if we had webpack disregard certain syntactic enhancements?

For instance: using optional chaining The application I'm working on is strictly for internal use, and it's specifically optimized for the latest Chrome browser. This means I can take advantage of syntactic sugar without needing to compile it, w ...

ReactJS Provider not passing props to Consumer resulting in undefined value upon access

Hey there! I've been facing an issue with passing context from a Provider to a consumer in my application. Everything was working fine until suddenly it stopped. Let me walk you through a sample of my code. First off, I have a file named AppContext.t ...

The module '@react-navigation/native' is missing or does not have its corresponding type declarations

I'm encountering an issue with my react-native app using expo and typescript. After installing the necessary libraries via npm, I can confirm they are available in the node_modules folder (see image below). https://i.sstatic.net/6riSc.png The same pr ...

Issue with Angular 2 TypeScript file not automatically transpiling to JavaScript (.js) upon saving within ASP.NET Core project in Visual Studio 2015

After making changes to app.component.ts, I have noticed that the modifications do not immediately appear in app.component.js. It seems like I need to manually build the project for the changes to take effect. My main objective is to see Angular 2 code up ...

Why is it not possible to return a header in a Typescript function?

I am new to using typescript and I have encountered an issue with a value for headers. Initially, it worked fine when directly set in the code. However, when I attempted to move it into a separate function that could be called, the functionality broke. Be ...

transitioning from angular 5 to the latest version of angular 7

After successfully migrating my application from Angular 5 to Angular 7, I made the necessary changes by replacing EventSource with EventSourcePolyfill as recommended during the application runtime. However, I am now encountering a peculiar issue. The cons ...

Implementing HTTP GET and POST requests in Angular 2 allows for the functionality of displaying, adding, and deleting objects within a list

Hey there, I'm completely new to dealing with HTTP and fetching data from the server. I've been scouring through various tutorials, examples, and questions on different platforms, but unfortunately, I haven't been able to find exactly what I ...

What are the best practices for preventing risky assignments between Ref<string> and Ref<string | undefined>?

Is there a way in Typescript to prevent assigning a Ref<string> to Ref<string | undefined> when using Vue's ref function to create typed Ref objects? Example When trying to assign undefined to a Ref<string>, an error is expected: co ...

update a property of a live object using an API request

Below is a sample of the service function I am working with: getByIdWithCategory(id: number): Observable<Product> { const category = new Category(); category.name = 'sample category'; return this.httpClient.get<Product> ...

Encountering type errors in React+Typescript while dynamically setting values in the change handler

I am currently working on dynamically generating a form based on an array of objects. The objective is to allow users to create accounts dynamically by clicking the Add User button and then submit the complete state object of users to the backend. Encoun ...

Struggling with generating a TypeScript declaration file

Struggling with creating a typescript definition file for a seemingly 'simple' npm module. Here are the key points: Problem: encounter an error when compiling TypeScript: play.ts(1,9): error TS2305: Module '"/to/the/dir/node_modules/geojs ...

Creating an Array in TypeScript

Is it possible to declare a global array in Typescript so that it can be accessed using "this" from any part of the code? In javascript, I would typically declare it as "var anArray=[]". What is the equivalent way of doing this in Typescript? Using anArra ...

Error in Typescript: Property 'timeLog' is not recognized on type 'Console'

ERROR in src/app/utils/indicator-drawer.utils.ts:119:25 - error TS2339: Property 'timeLog' does not exist on type 'Console'. 119 console.timeLog("drawing") I am currently working with Typescript and Angular. I have ...

Convert a TypeScript array of strings to a boolean array: a step-by-step guide

Upon receiving a list of objects from the front end as: item=["false","true"] I proceed to check a column within my records to identify values containing "true" or "false" using the following code: this.records.filter(x=> items.includes(x.column)) Unf ...

NextJS: Route Handler encountering Method Not Allowed (405) error when trying to redirect

Current NextJs version is 13.4.3 I have set up a route handler to capture POST requests. For more information on route handlers, please refer to the documentation at [https://nextjs.org/docs/app/building-your-application/routing/router-handlers] In this ...

A step-by-step guide on dynamically altering button colors in Angular 2

Struggling to dynamically change the color of my button, any suggestions? <a class="button buttonaquacss button-mini button-aqua text-right pull-right" (click)='send(button,detail.profile_id)' #button [ngStyle]="{'background-color' ...

Choose does not showcase the updated value

My form contains a form control for currency selection Each currency object has the properties {id: string; symbol: string}; Upon initialization, the currency select component loops through an array of currencies; After meeting a specific condition, I need ...