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的类型是unknow?
如果没有test<DogProps, Dog>(Dog)
,是否可以得到正确的类型?
非常感谢!
答案 0 :(得分:3)
这是通用解析工作方式的一个副作用,打字稿发现参数中引用了T
,因此它尝试解决该问题,但是约束基于U
,因此它试图首先解决。由于U
没有出现在参数列表中的任何地方,因此它无法解析,因此以unknown
如果您确保参数列表中包含U
,则可以确保打字稿仅通过查看输入即可解决它,而不必先弄清楚T
:
function test<U, T extends Base<U>>(Cor: new()=>(T & Base<U>)): [U, T] {
// ^here^
}
这应该可以解决问题:)