为什么打字稿函数参数类型推断失败? [英] 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
我是打字稿新手.
我认为我写的代码是对的.但它没有按预期工作.
为什么 state1 的类型是未知的?
我可以在没有 test
的情况下获得正确的类型吗?
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)
?
非常感谢!!!
推荐答案
这是泛型解析工作方式的副作用,打字稿看到 T
在参数中被引用,因此它试图解析它,但约束是基于 U
所以它试图首先解决这个问题.因为 U
没有出现在参数列表中的任何地方,它无法解析它所以它以 unknown
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
如果您确保 U
出现在参数列表中,您可以确保打字稿能够通过查看输入来解决它,而无需弄清楚 T
首先:
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 :)
这篇关于为什么打字稿函数参数类型推断失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!