【问题标题】:Typescript Dynamically Check if value is of a Union Type打字稿动态检查值是否属于联合类型
【发布时间】:2021-02-16 06:37:23
【问题描述】:

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

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

例如我想使用如下语法:

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

【问题讨论】:

  • Typescript 的类型在运行时不存在;您的问题需要在 JavaScript 领域解决,然后 Typescript 仅用于在编译时检查解决方案是否正常。在这种情况下,您的联合类型来自对象的键,因此请在运行时检查字符串是否是该对象中的键。
  • 只能在类型级别上做

标签: typescript typechecking union-types


【解决方案1】:

我会检查给定的方法名称是否是 mathFn 的键。不幸的是,检查不足以让编译器注意到字符串是 SupportedMathFunction 类型,您需要使用 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];
  }
}

【讨论】:

  • 非常感谢@Lesiak。我认为您的解决方案使用我正在寻找的类似语法来完成这项工作。
猜你喜欢
  • 2019-05-26
  • 1970-01-01
  • 2015-05-24
  • 1970-01-01
  • 2018-05-14
  • 1970-01-01
  • 2019-11-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多