英文:
How to create function that will return a function with type inference using generics in typescript
问题
// 这是返回的函数
const suppliedFunction = <T>(args: T) => {
return true;
}; // 这是返回的函数
// 所以我可以这样使用它
suppliedFunction({ prop: "value" });
// 函数生成器,从参数返回供应的函数
// 提供的函数应该返回一个布尔值
function generateFunction(fn: <T>(args: T) => boolean) {
return fn;
}
// 但是这段代码给我一个错误
// 属性'prop'在类型'unknown'上不存在
const resultFunction = generateFunction(({ prop }) => {
return true;
});
// 我的目标是我可以根据生成的函数来使用resultFunction进行类型推断(而不是显式编写类型)
// 这应该引发错误
// 类型为'string'的参数无法分配给类型为'{ prop: any; }'的参数
resultFunction('text');
// 这应该没问题
resultFunction({ prop: "winter" });
英文:
Let say i want to run generateFunction() that will return this function:
// This is the returned function
const suppliedFunction = <T>(args: T) => {
return true;
}; // This is the returned function
// so I can use it like this
suppliedFunction({ prop: "value" });
I decided to create the generatorFunction like this:
// Function generator, returning supplied function from the parameter
// The supplied function should returning a boolean
function generateFunction(fn: <T>(args: T) => boolean) {
return fn;
}
// But this code gives me an error
// Property 'prop' does not exist on type 'unknown'
const resultFunction = generateFunction(({ prop }) => {
return true;
});
My goal is i could use resultFunction with type inference based on generated function (not by explicitly writing the type
// This should gives an error
// Argument of type 'string' is not assignable to parameter of type '{ prop: any; }'
resultFunction('text');
// This should be OK
resultFunction({ prop: "winter" });
How do we really implement this generics for my case? Thakks in advance.
答案1
得分: 0
实际上,我在解决了三天的问题后,终于找到了我想要的东西,感谢[@jcalz](https://stackoverflow.com/users/2887218/jcalz)在[此答案](https://stackoverflow.com/questions/51851677/how-to-get-argument-types-from-function-in-typescript)中提供的帮助,我可以使用基于泛型的自定义ArgumentTypes和custom ReturnTypes。由于在我的项目中,使用typescript的Parameters<>和ReturnType<>工具不起作用,所以我决定使用该答案中提供的自定义实用程序,然后我创建了这个。
它工作得很好,动态地支持操作重载函数,因此可以保证类型安全。如果你不希望将文档对象模型值作为参数传递并从提供的函数返回类型传递给生成器,你可以将其添加到Serializables类型以限制类型。
[在这里查看它的运行情况](https://tsplay.dev/mpxBzm)
英文:
Actually i just found what I wanted, after 3 days of solving this, thanks to @jcalz from this post answer i could use custom ArgumentTypes and custom ReturnTypes based on generics. Somehow, using Parameters<> and ReturnType<> utilities from typescript is not working for my project so I decided to use custom utility provided from that answer, then I made this
type Serializables =
| Function
| PropertyDescriptor
| Document
| Omit<RegExp, "lastIndex">
| never;
type SerializableParam<Serializable> = Serializable extends Serializables
? unknown
: Serializable;
type SerializableReturnType<Serializable> =
Serializable extends Serializables | void ? never : Serializable;
type ArgumentTypes<F extends Function> = F extends (...args: infer A) => any
? A
: never;
type ReturnType<F extends Function> = F extends (...args: any) => infer A
? A
: never;
interface SupplierFunction<T, Payload> extends Function {
(arg0?): Payload extends undefined
? never
: SerializableReturnType<ReturnType<T & Function>>;
(arg0: SerializableParam<Payload>): SerializableReturnType<
ReturnType<T & Function>
>;
(...arg0: SerializableParam<Payload>[]): Payload extends undefined
? never
: SerializableReturnType<ReturnType<T & Function>>;
}
export default function generateFunction<F>(
fn: F & SupplierFunction<F, ArgumentTypes<F & Function>[0]>
) {
return async (payload: ArgumentTypes<F & Function>[0]) => {
const result: SerializableReturnType<ReturnType<F & Function>> =
await new Promise((resolve) => {
resolve(fn(payload));
});
return await result;
};
}
It works like charm, dynamically and also support manipulating overloading functions so it can be typesafed. If you dont want document object model value passed as parameter and return types from the supplied function to the generator, you can add it to Serializables type to restrict the types.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论