简体   繁体   中英

why does typescript function parameter type infer failed?

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 right. But it does not work as expected.
Why state1's type is unknow?
Can I get the right type without test<DogProps, Dog>(Dog) ?

much thanks!!!

This is a side effect of how generic resolution works, typescript sees that T is referred to in the arguments so it tries to resolve it, but the constraint is based on U so it tries to resolve that first. Because U doesn't appear anywhere in the argument list, it can't resolve it so it ends up unknown

If you ensure that U is present in the arguments list you can ensure that typescript will be able to resolve it from just looking at the input without having to figure out T first:

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

This should fix the issue :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM