Search code examples
typescripttypecheckingunion-types

Typescript Dynamically Check if value is of a Union Type


I have generated a Union type of my supported methods and I want to check that the method is one of my supported methods and then dynamically call the method. I know that I can check this by using an array of supported methods names and using methods like includes but I'm wondering if it is possible with type checking or not?

import * as mathFn from './formula/math';
type SupportedMathFunction = keyof typeof mathFn;
//'fnA'| 'fnB' | ...

for example I want to use syntax like:

if( methodName is SupportedMathFunction){
//do something
}

Solution

  • I'd check if given method name is a key of mathFn. Unfortunatly, the check is not enough for the compiler to notice that the string is of type SupportedMathFunction , you need to use User-Defined Type Guards

    function isMemberOfMathFn(methodName: string): methodName is keyof typeof mathFn {
      return methodName in mathFn;
    }
    
    
    function test(methodName: string) {
      if (isMemberOfMathFn(methodName)) {
        const method = mathFn[methodName];
      }
    }