【问题标题】:Idiomatic Typescript Enum Discriminated Union惯用的 Typescript 枚举有区别的联合
【发布时间】:2017-10-03 09:27:45
【问题描述】:

从 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 = () => {};

【问题讨论】:

    标签: typescript enums idioms discriminated-union


    【解决方案1】:

    这是惯用的方式吗

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

    更多

    【讨论】:

    • 我一直在看你的书 :) 谢谢!是否可以根据参数推断某些可区分联合的返回类型?即如果代码是 A 类型,我知道返回类型将是 B 类型。
    • 是的。返回类型的联合的所有返回语句。例如如果您在代码的不同部分返回 stringnumber,则返回类型被推断为 string | number ?
    猜你喜欢
    • 1970-01-01
    • 2011-10-23
    • 2013-10-27
    • 1970-01-01
    • 2012-12-12
    • 2020-08-10
    • 1970-01-01
    • 2018-10-12
    相关资源
    最近更新 更多