Hi everyone! I need some help with TypeScript to achieve type safety for an object while building it. I have a function foo that receives an object with properties. Let's say it has two properties, foo and baz. Each property will have the same config object. The config object has the following shape:
type ConfigObject = {
action: (...args: any[]) => Promise<any>;
dependencies: string[];
}
The types are quite broad, but this is just for demonstration purposes. I want the type system to infer the arguments of my action function when a config object specifies a dependency. Instead of any, it should infer an object with properties equal to my dependency array (which will have type safety for only introducing properties of my initial root object), and with the values equal to the return type of each of those dependencies, respectively.
For example:
const obj = {
foo: {
action: () => {
return [1, 2, 3];
},
},
baz: {
action: ({ foo }) => {
const fooResult = foo; // should be inferred as [1, 2, 3]
fooResult.forEach((value) => console.log(value)); // 1, 2, and 3
},
},
};
Please note that the dependencies array could be optional, and we want to maintain type safety for it as well. How can I achieve this level of type safety and inference for my object?
Any help would be greatly appreciated!