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
CodePudding user response:
After reviewing the marked as duplicated question a possible solution will be (not the most optimal because I have to change the behavior of the function):
function test(...args: [a: string] | [a: number, b: number]): number | string {
let a = args[0];
let b = args[1];
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");
}