我不明白为什么类型记录不能正确地推断出下列情况下的类型,这涉及到类型参数的推断。(这个问题类似于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> {}注意:为了简化方法签名,我使用了角的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的定义中推断出ValueDialog和R,但事实并非如此。
当然,我可以通过手动指定类型来修复这个问题,但这是非常糟糕的。我也可以通过使P和R相同来修复它,但这不是我想要的功能。
如何定义show()以使其正确地推断R
发布于 2018-11-23 15:12:11
可以使用条件类型从基类型中提取类型R参数。您需要以某种方式使用R类型,这样才能起作用:
export interface Type<T> extends Function {
new (...args: any[]): T;
}
class BaseDialog<P, R> {
value: R //we need to use R in some way for the parameter to make a difference
}
class ValueDialog extends BaseDialog<string, number> {}
type ExtractResult<T extends BaseDialog<any, any>> = T extends BaseDialog<any, infer R> ? R : never;
// A function that shows the dialog
declare function show<T extends BaseDialog<P, any>, P>(dlg: Type<T>, param: P): Promise<ExtractResult<T>>;
show(ValueDialog, "name").then(r => console.log(r)); // r is now stringhttps://stackoverflow.com/questions/53449020
复制相似问题