2017-05-05 46 views
0

由于打字稿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); 
    } 
} 

作为打字稿2.3

  • 是这种习惯的方法去做这个?
  • 我们能否推断someParam的类型而不投射?
  • 我们是否能够简化类型定义,可能使用泛型,更改函数参数等,所以我们只需要定义最终函数?
  • 是否有可能宣布的功能像consts:const getInstance =() => {};

回答

0

这是如果需要例如使用类型断言来做到这一点

号的惯用方式someParam as OtherType1这是不安全的。

更多
+0

我一直在看你的书:)谢谢!是否有可能根据参数推断出某种歧视联盟的返回类型?即如果代码是类型A,我知道返回类型是类型B. – chris

+0

是的。返回类型的联合的所有返回语句。例如如果你在你的代码的不同部分返回一个'string'和'number',返回类型被推断为'string | number' – basarat