【发布时间】:2019-04-22 20:49:08
【问题描述】:
考虑以下代码:
interface FooBarTypeMap {
FOO: FooInterface;
BAR: BarInterface;
}
type FooBarTypes = "FOO" | "BAR";
export interface FooBarAction<T extends FooBarTypes> {
type: T;
data: FooBarTypeMap[T];
}
const doSomthingBasedOnType = (action: FooBarAction<FooBarTypes>): void => {
switch (action.type) {
case "FOO":
FooAction((action as FooBarAction<"FOO">));
}
};
const FooAction = (action: FooBarAction<"FOO">): void => {
//do something with action.data
};
现在我想避免在 doSomthingBasedOnType 中看到的强制转换(作为 FooBarAction 的操作),如果接口使它成为此开关内的唯一可能性,则作为定义。我可以在我的代码中更改一些内容以使其正常工作,还是这只是 TypeScript 中的一个错误?
【问题讨论】:
标签: typescript casting typescript-typings typescript-generics