Home > Enterprise >  Dynamic types depending on number of parameters in IDE
Dynamic types depending on number of parameters in IDE

Time:06-22

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 and b 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

Function one parameter

But when passed two, or a comma is added, the behavior changes to show this:

Function two parameters

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 enter image description here

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");
}
  • Related