【发布时间】: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