Typescript 惯用类型脚本枚举鉴别并集

Typescript 惯用类型脚本枚举鉴别并集,typescript,enums,idioms,discriminated-union,Typescript,Enums,Idioms,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: En

从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的类型
  • 我们是否能够简化类型定义,可能使用泛型,修改函数参数,等等,所以我们只需要定义最终的函数
  • 是否可以将函数声明为常量,如:
    constgetinstance=()=>{}
这是惯用的方法吗

不可以。如果您需要使用类型断言,例如,
someParam作为OtherType1
它是不安全的

更多
  • 类型断言的不安全性:
  • 惯用的方法是使用判别属性,而不是函数重载。示例:

我一直在读你的书:)谢谢!是否有可能根据一个参数推断出某个有区别的并集的返回类型?i、 e.如果代码为A型,我知道返回类型为B型。是。返回类型的联合的所有返回语句。e、 g.如果在代码的不同部分返回
字符串
数字
,则返回类型推断为
字符串|数字