Looking to create a function with two different calling options:
function visit(url: string, options: Partial<VisitOptions>): void
function visit(options: Partial<VisitOptions> & {url:string}): void
I'm exploring the most effective way to implement this.
This is what my current code looks like:
type VisitOptions = {
timeout: number
}
function visit(url: string, options: Partial<VisitOptions>): void;
function visit(options: Partial<VisitOptions> & { url: string }): void;
function visit(...params: any): void {
let finalOptions: Partial<VisitOptions> & { url: string };
if (params.length === 1) {
finalOptions = params[0];
} else {
const [url, options] = params;
finalOptions = {
url,
...options
}
}
console.log(finalOptions);
// ... more
}
In the actual implementation of the function, you'll find:
function visit(...params: any): void
I am using ...params: any
as a parameter, which works but sacrifices type safety within the function body.
Any suggestions for a better approach?