[英]Typescript type inference from type parameters
我不明白在以下涉及從類型參數推斷的情況下,為什么Typescript無法正確推斷類型。 (此問題與TypeScript類型推斷問題相似,但情況有所不同。不過,答案可能是相同的,因為我很不幸!)
// 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
?
您可以使用條件類型從基本類型中提取類型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 string
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.