Let's say I have a function that receives a callback and it will return the object returned by the callback, Is there any ways that I can achieve something like this ?
const my_object = my_function<A extends string, B extends boolean>
("my_object", true, () => ({
helloWorld: () => {},
greet: () => {},
// etc...
}));
So that I can call it like
my_object.helloWorld();
my_object.greet();
What I did now is just something like this
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();
}
Above code is okay to use, but I want something more strict, because in the case
// @ts-expect-error
my_object.func_not_exist() // TypeScript do not blame on these runtime error.
And I don't want to declare the type by myself, which is something like
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 is always required, should not and cannot remove, in this case, is it possible to do the infer stuff ?
In the real case, A is an interface extending an object, and B is the key of A, so for type-safe, they are required.