Trying to create a function that can be invoked with multiple arguments or a single object acting as a container for those arguments.
Here's an example of what I've tried:
export type ExecutionArgs = {
input: Observable<string>,
whatever: SomeOtherType,
foo?: string,
bar?: number,
};
function execute(
args: ExecutionArgs,
...rest: any[]
): Observable<string>;
function execute(
input: Observable<string>,
whatever: SomeOtherType,
foo?: string,
bar?: number,
): Observable<string>;
function execute(
inputOrArgs,
whatever,
foo,
bar,
) {
// Extract arguments from object args if provided.
if (arguments.length === 1) {
return doThings(
inputOrArgs.input,
inputOrArgs.whatever,
inputOrArgs.foo,
inputOrArgs.bar,
);
}
return doThings(
inputOrArgs,
whatever,
foo,
bar,
);
}
When using my function, the types are correctly detected. For instance, errors are displayed for input
and bar
in the following lines:
execute('a', 'b', 'c', 'd');
execute({ input: 'a', whatever: 'b', foo: 'c' bar: 'd' });
However, within the function itself, TypeScript only identifies the type as any
when hovering over variables or object properties.
What is the correct way to define my function?