从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 回答
不,如果您需要使用类型断言,例如
someParam as OtherType1
这是不安全的 .更多
类型断言不安全:https://basarat.gitbooks.io/typescript/docs/types/type-assertion.html
惯用的方法是使用判别属性而不是函数重载 . 示例:https://basarat.gitbooks.io/typescript/docs/types/discriminated-unions.html