[英]How do I get typescript to infer the return type of a function based on the return type on a function of its arguments
So this function is supposed to take in an array of objects that satisfy the interface TransactionActionModel
.所以这个 function 应该接受满足interface TransactionActionModel
的对象数组。 which means they must all have a function called "save" that receives arguments of the interface SaveOptions
.这意味着它们都必须有一个名为“save”的 function 接收interface SaveOptions
。
Currently the return type for this saveUsingTransaction
function is Promise<any[]>
.目前这个saveUsingTransaction
function 的返回类型是Promise<any[]>
。
interface TransactionActionModel {
save: ({ session }: SaveOptions) => any;
}
const saveUsingTransaction = async (
newEntities: TransactionActionModel[]
) => {
const returnsArray = [];
// Create Transaction
const session = mongoDBWrapper.client.startSession();
try {
// Start Transaction
session.startTransaction({});
for (const entity of newEntities) {
const resolve = await entity.save({ session });
returnsArray.push(resolve);
}
// End Transaction
await session.commitTransaction();
return returnsArray;
} catch (error) {
await session.abortTransaction();
throw error;
} finally {
await session.endSession();
}
};
Is there any way to get the return type of the saveUsingTransaction
to match the return type of the save function on the entities I pass into the saveUsingTransaction
.有没有办法让saveUsingTransaction
的返回类型与我传递到saveUsingTransaction
的实体上的保存 function 的返回类型相匹配。
For Example
const person = {
phone: "0233224444",
save: ({session}):Person => {
return this
}
}
const cat = {
weight: "30kg",
save: ({session}): Animal => {
return this
}
}
const results = saveUsingTransaction([person, cat])
the type on the results variable should be ==> "[Person, Animal]"
Your interface should be generic:您的界面应该是通用的:
interface TransactionActionModel<T> {
save: ({ session }: SaveOptions) => T;
}
As well as your function:以及您的 function:
const saveUsingTransaction = async <A extends TransactionActionModel<any>[]>(
newEntities: [...A]
): { [K in keyof A]: ReturnType<A[K]["save"]> } => {
Use [...A]
to infer A
as a tuple, then use that tuple in the return type by mapping over its elements and changing them to the return type of their save function.使用[...A]
将A
推断为一个元组,然后通过映射其元素并将它们更改为它们保存 function 的返回类型,在返回类型中使用该元组。 TypeScript will infer the generic in the interface in [...A]
. TypeScript 将在[...A]
的接口中推断泛型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.