Search code examples
javascripttypescripttype-conversion

What's the best way to switch on union types in Typescript? For example number | string


Suppose I have the following class:

export class Complex {

/**
 * Representation of a complex number
 *
 * @param _re
 * @param _im
 */
constructor(private _re: number, private _im: number = 0) {

}

/** implementation details truncated **/
}

Now I want to write the following function:

function add(z1: Complex | number, z2: Complex | number): Complex {
   if (/** z1 is number **/) {
        z1 = new Complex(z1)
   }
   if (/** z2 is number **/) {
        z2 = new Complex(z2)
   }
   return z1.add(z2)
}

What's the cleanest and most idiomatic way to write this in typescript?


Solution

  • The most idiomatic way to do this given your code template is to use a typeof type guard as follows:

    function add(z1: Complex | number, z2: Complex | number): Complex {
      if (typeof z1 === "number") {
        z1 = new Complex(z1);
      }
      if (typeof z2 === "number") {
        z2 = new Complex(z2);
      }
      return z1.add(z2)
    }
    

    Playground link to code