【问题标题】:why does typescript function parameter type infer failed?为什么打字稿函数参数类型推断失败?
【发布时间】:2021-01-03 12:12:26
【问题描述】:
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

我是打字稿的新手。
我认为我写的代码是对的。但它没有按预期工作。
为什么 state1 的类型未知?
没有test&lt;DogProps, Dog&gt;(Dog),我能得到正确的类型吗?

非常感谢!!!

【问题讨论】:

    标签: typescript typescript-typings type-inference typescript-generics


    【解决方案1】:

    这是泛型解析如何工作的副作用,typescript 看到参数中引用了T,因此它尝试解析它,但约束基于U,因此它首先尝试解决它。因为U 没有出现在参数列表中的任何位置,所以它无法解析它,所以它以unknown 结束

    如果您确保 U 出现在参数列表中,您可以确保 typescript 能够通过仅查看输入来解决它,而无需首先弄清楚 T

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

    这应该可以解决问题:)

    【讨论】:

    • 你是我的上帝。你救了我的命。
    • 我当然希望你的生活不要依赖于这样的事情?。快乐编码! ?
    • 现在我明白了第一段,我的代码不起作用的原因。但我仍然不明白第二段,为什么你的代码有效。特别是without having to figure out T first。因为return param仍然需要type T。你能解释更多细节吗?
    • 假装你是打字稿,你正在查看参数的类型并且你试图弄清楚U应该解决什么。但是U 没有在输入参数的任何地方指定,只有T,那么你怎么知道U 是什么?在某些时候,打字稿可能会更新以应对这种情况,但至少在今天使用(T &amp; (Constraint of T)) 工作正常。
    • 作为人类,我们知道Dog extends Base,那么U's type必须是DogProps。但是打字稿似乎不够聪明。顺便说一句,你能推荐任何书籍或网站或文章来学习高级打字技能,比如how generic resolution works。看来打字稿文档没有这些东西。
    猜你喜欢
    • 2016-08-03
    • 1970-01-01
    • 1970-01-01
    • 2020-03-22
    • 1970-01-01
    • 1970-01-01
    • 2020-03-01
    • 2021-07-22
    • 2021-10-27
    相关资源
    最近更新 更多