惯用语打字记Enum歧视联盟

时间:2017-05-05 02:58:07

标签: typescript enums idiomatic discriminated-union

从typescript 2.0开始,您可以使用带有枚举的歧视联合作为判别式:

export function getInstance(code: Enum.Type1, someParam: OtherType1): MyReturnType1;
export function getInstance(code: Enum.Type2, someParam: OtherType2): MyReturnType2;
export function getInstance(code: Enum, someParam: UnionOfOtherTypes): UnionOfReturnTypes {
  switch (code) {
    case Enum.Type1:
      return new ReturnType1(someParam as OtherType1);
    case Enum.Type2:
      return new ReturnType2(someParam as OtherType2);
  }
}

从TypeScript 2.3开始

  • 这是惯用的方法吗?
  • 我们是否能够推断someParam的类型而不进行投射?
  • 我们是否能够简化类型定义,可能使用泛型,更改函数参数等,所以我们只需要定义最终函数?
  • 是否可以将函数声明为:const getInstance = () => {};

1 个答案:

答案 0 :(得分:0)

  

这是执行此操作的惯用方式

没有。如果你需要使用类型断言,例如someParam as OtherType1这是不安全的。

更多