Imagine that I have a function that behaves differently when passed one parameters vs two. For example:
function test(a: string | number, b?: number ) {
if(typeof b !== 'undefined' && typeof a === "number"){
return a * b
}
if (typeof a === "string" && typeof b === "undefined"){
return a.toUpperCase()
}
throw new Error("Incorrect Params");
}
Function behavior:
When only
a
is present and it is a string, convert it to uppercase.When both
a
andb
are present, both must be numbers, and multiply them.Any other type of combination throws an error
The question is, can it be typed in such a way that this behavior is reflected in the IDE?
That is, when only one parameter is passed to it, the IDE will show this
But when passed two, or a comma is added, the behavior changes to show this:
This would allow to avoid error during code development.
Clarification: The exposed function is only an example and not a real use case. Still I think this would be very useful and I have seen it implemented in the Google Apps Script IDE. I would like to know what the internal mechanism is, and if it can be extended to VSCode using only Typescript.