Typescript 惯用类型脚本枚举鉴别并集
从typescript 2.0开始,您可以使用带有枚举的判别联合作为判别式,如下所示: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
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
它是不安全的
更多
- 类型断言的不安全性:
- 惯用的方法是使用判别属性,而不是函数重载。示例:
字符串
和数字
,则返回类型推断为字符串|数字