首页 > 解决方案 > 推断嵌套的通用参数并从函数中返回它

问题描述

我有一个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,
});

在得到结果之前,一切都是正确的。结果是 type of Typegoose,但它应该是 type AccountClass。我该如何解决这个问题?谢谢你的帮助。

编辑:解决误解;我可以传递类型,但我构建它的全部原因是不传递类型并使其自动推断。难道没有办法吗?

标签: javascripttypescriptgenericsinterfacenested

解决方案


我认为您还应该在调用函数时传递类型。

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> ...

推荐阅读