【发布时间】:2018-11-22 22:05:46
【问题描述】:
这是此处解决的问题的延续:Avoid typescript casting inside a switch 使用它,我设置了这样的类型:
interface FooInterface {
foo: number,
type: "FOO"
}
interface BarInterface {
bar: number,
type: "BAR"
}
interface FooBarTypeMap {
FOO: FooInterface;
BAR: BarInterface;
}
type FooBarTypes = "FOO" | "BAR";
export type FooBarAction<T extends FooBarTypes> = T extends any ? {
type: T;
data: FooBarTypeMap[T];
} : never;
//I want to use this to create a function which returns a FooBarAction, of either type. But the following code fails on typings:
const createFooBarAction = <T extends FooBarTypes>(fooBarData: FooBarTypeMap[T]): FooBarAction<T> => ({
type: fooBarData.type,
data: fooBarData
});
将输入或返回值更改为 any 有效,但显然我想避免这种情况。我尝试创建一个 FooInterface 和 BarInterface 扩展的 AllFooBarInterfaces,如下所示:
// Seems to not have any effect, but it might be a good practice anyway.
interface AllFooBarInterfaces<T extends FooBarTypes> {
type: T
}
interface FooInterface extends AllFooBarInterfaces<"FOO">{
foo: number,
}
interface BarInterface extends AllFooBarInterfaces<"BAR">{
bar: number,
}
虽然我可以对上述接口和类型的定义进行更改,但我仍然需要支持原始问题中提出的案例,该案例包含在下面以便于访问。
const doSomthingBasedOnType = (action: FooBarAction<FooBarTypes>): void => {
switch (action.type) {
case "FOO":
FooAction(action);
}
};
const FooAction = (action: FooBarAction<"FOO">): void => {
//do something with action.data
};
【问题讨论】:
标签: typescript