I have an IModelDefinition
like this:
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:
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. 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.
public async getSingleMatch<MT extends Typegoose = AccountClass, QT>(
definition: ModelDefinition<MT, QT>,
doc: QT
): Promise<MT> ...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.