Typescript动态检查值是否为联合类型

Typescript动态检查值是否为联合类型,typescript,typechecking,union-types,Typescript,Typechecking,Union Types,我已经生成了我支持的方法的联合类型,我想检查该方法是否是我支持的方法之一,然后动态调用该方法。 我知道我可以通过使用受支持的方法名数组和includes等方法来检查这一点,但我想知道是否可以使用类型检查 import * as mathFn from './formula/math'; type SupportedMathFunction = keyof typeof mathFn; //'fnA'| 'fnB' | ... 例如,我想使用如下语法: if( methodName is Sup

我已经生成了我支持的方法的联合类型,我想检查该方法是否是我支持的方法之一,然后动态调用该方法。 我知道我可以通过使用受支持的方法名数组和includes等方法来检查这一点,但我想知道是否可以使用类型检查

import * as mathFn from './formula/math';
type SupportedMathFunction = keyof typeof mathFn;
//'fnA'| 'fnB' | ...
例如,我想使用如下语法:

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

我会检查给定的方法名是否是mathFn的键。不幸的是,检查不足以让编译器注意到字符串的类型是SupportedMathFunction,您需要使用


我会检查给定的方法名是否是mathFn的键。不幸的是,检查不足以让编译器注意到字符串的类型是SupportedMathFunction,您需要使用


Typescript的类型在运行时不存在;您的问题需要在JavaScript中解决,然后Typescript只是用于检查解决方案在编译时是否正常。在这种情况下,您的联合类型来自对象的键,因此请在运行时检查字符串是否是该对象中的键;您的问题需要在JavaScript中解决,然后Typescript只是用于检查解决方案在编译时是否正常。在本例中,您的联合类型来自对象的键,因此请在运行时检查字符串是否是该对象中的键。只能在类型级别执行此操作。非常感谢@Lesiak。我认为您的解决方案使用了我所寻找的类似语法。非常感谢@Lesiak。我认为您的解决方案与我所寻找的语法类似。
function isMemberOfMathFn(methodName: string): methodName is keyof typeof mathFn {
  return methodName in mathFn;
}


function test(methodName: string) {
  if (isMemberOfMathFn(methodName)) {
    const method = mathFn[methodName];
  }
}