【发布时间】:2019-04-26 04:53:30
【问题描述】:
我不明白为什么 Typescript 在以下涉及类型参数推断的情况下无法正确推断类型。 (这个问题与TypeScript type inference issue 类似,但情况有些不同。答案可能是一样的,但我只是不走运!)
// A base class for a dialog taking parameter of type P
// and returning result of type R.
class BaseDialog<P, R> { p: P; r: R; }
class ValueDialog extends BaseDialog<string, number> {}
// A function that shows the dialog
show<T extends BaseDialog<P, R>, P, R>(dlg: Type<T>, param: P): Promise<R> {}
注意:为了简化方法签名,我使用的是 Angular 的Type:
export interface Type<T> extends Function {
new (...args: any[]): T;
}
现在,当我调用方法show,如下,R类型没有正确推断:
show(ValueDialog, "name").then(r => console.log(r));
编译器推断:
T = ValueDialog
P = string
R = {}
由于T 被正确推断,您可能认为编译器可以从ValueDialog 的定义推断P 和R,但事实并非如此。
当然,我可以通过手动指定类型来解决这个问题,但这非常难看。我也可以通过使P 和R 相同来修复它,但这不是我想要的功能。
如何定义show() 以便正确推断R?
【问题讨论】: