Is there a way to create a function that receives a callback and returns the object returned by that callback? Here's an example of what I'm trying to achieve:
const my_object = my_function<A extends string, B extends boolean>
("my_object", true, () => ({
helloWorld: () => {},
greet: () => {},
// etc...
}));
This would allow me to call it like this:
my_object.helloWorld();
my_object.greet();
Currently, I have implemented the function as follows:
const my_function = <A extends string, B extends boolean>(Name: A, other:B, callback: () => Record<string, Function>) => {
// some code for A
// some code for B
// then
return callback();
}
Although the above code works fine, I am looking for a more strict approach. For example, I want TypeScript to catch runtime errors such as:
// @ts-expect-error
my_object.func_not_exist()
I do not want to manually declare types, like in the following example:
I don't want to do the following...
const my_function = <T>(callback: () => T): T => {
return callback();
}
const my_object = my_function<"MyObject", true, { helloWorld: () => void; greet: () => void }>("MyObject", true, () => ({
helloWorld: () => {},
greet: () => {},
}))
p.s. the first two params are always required and cannot be removed. Is it possible to infer these types in this scenario?
In real cases, A is an interface extending an object, and B is the key of A, making them required for type-safety.