从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开始
const getInstance = () => {};
答案 0 :(得分:0)
这是执行此操作的惯用方式
没有。如果你需要使用类型断言,例如someParam as OtherType1
这是不安全的。