简体   繁体   English

为什么打字稿函数参数类型推断失败?

[英]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?为什么 state1 的类型是未知的?
Can I get the right type without test<DogProps, Dog>(Dog) ?我可以在没有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.这是通用解析如何工作的副作用,打字稿看到T在参数中被引用,因此它尝试解决它,但约束基于U因此它首先尝试解决它。 Because U doesn't appear anywhere in the argument list, it can't resolve it so it ends up unknown因为U没有出现在参数列表中的任何地方,所以它无法解析它所以它最终是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:如果您确保U存在于参数列表中,您可以确保打字稿能够通过查看输入来解决它,而无需先找出T

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

This should fix the issue :)这应该可以解决问题:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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