首页 文章

惯用语打字记Enum歧视联盟

提问于
浏览
0

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

As of TypeScript 2.3

  • 这是惯用的方法吗?

  • 我们能否在不进行投射的情况下推断someParam的类型?

  • 我们能够简化类型定义,可能使用泛型,改变函数参数等,所以我们只需要定义最终函数吗?

  • 是否可以将函数声明为如下所示: const getInstance = () => {};

1 回答

相关问题