[英]Inferring Nested Generic Parameter and Returning It from Function
我有一個這樣的IModelDefinition
:
export interface IModelDefinition<MT extends Typegoose, QT> {
model: new () => MT;
}
QT並不是直接在界面本身中使用的,而是作為輔助函數傳遞給其他功能的,因此Typescript可以自動推斷QT:
public async getSingleMatch<MT extends Typegoose, QT>(
definition: ModelDefinition<MT, QT>,
doc: QT
): Promise<MT> ...
我這樣調用該函數:
// Account is a ModelDefinition<AccountClass, {identifier: string} and
// if I remove the identifier string, it gives an error as I expect it to.
const account = await getSingleMatch(Account, {
identifier: params.identifier,
});
一切正常,直到得到結果。 結果為Typegoose
類型,但應改為AccountClass
類型。 我該如何解決? 謝謝你的幫助。
編輯:解決誤會; 我可以傳遞類型,但是構建此文件的全部原因是不傳遞類型並使其自動推斷。 沒辦法嗎?
我認為您在調用函數時也應該傳遞類型。
const account = await getSingleMatch<AccountClass, {identifier: string}>(Account, {identifier: params.identifier})
現在,如果您不想在每次調用該函數時都希望傳遞該類型,並希望其推斷AccountClass
,那么只需將默認類型AccountClass
分配給泛型類型。
public async getSingleMatch<MT extends Typegoose = AccountClass, QT>(
definition: ModelDefinition<MT, QT>,
doc: QT
): Promise<MT> ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.