简体   繁体   English

推断嵌套的通用参数并从函数中返回

[英]Inferring Nested Generic Parameter and Returning It from Function

I have an IModelDefinition like this: 我有一个这样的IModelDefinition

export interface IModelDefinition<MT extends Typegoose, QT> {
  model: new () => MT;
}

QT isn't directly used in the interface itself, but it is passed as a helper to other functions, like this so Typescript can infer the QT automatically: QT并不是直接在界面本身中使用的,而是作为辅助函数传递给其他功能的,因此Typescript可以自动推断QT:

public async getSingleMatch<MT extends Typegoose, QT>(
    definition: ModelDefinition<MT, QT>,
    doc: QT
): Promise<MT> ...

And I call the function like this: 我这样调用该函数:

// 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,
});

Everything is right until getting the result. 一切正常,直到得到结果。 The result is type of Typegoose , but it should be of type AccountClass instead. 结果为Typegoose类型,但应改为AccountClass类型。 How can I solve this? 我该如何解决? Thanks for your help. 谢谢你的帮助。

EDIT: To resolve misunderstanding; 编辑:解决误会; I can pass the types, but the whole reason I'm building this is to not to pass the types and make it infer automatically. 我可以传递类型,但是构建此文件的全部原因是不传递类型并使其自动推断。 Isn't there a way? 没办法吗?

I think you should also pass the type while calling the function. 我认为您在调用函数时也应该传递类型。

const account = await getSingleMatch<AccountClass, {identifier: string}>(Account, {identifier: params.identifier})

Now if you don't want the type to be passed every time you call the function and want it to infer the AccountClass , so just assign the default type AccountClass to the generic type. 现在,如果您不想在每次调用该函数时都希望传递该类型,并希望其推断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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM