Consider the following code:
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
};
Now I would like to avoid the casting (action as FooBarAction<"FOO">) as seen in doSomthingBasedOnType, as the very definition if the interface makes this the only possibility inside this switch. Is there something I can change in my code for this to work, or is this simply a bug in TypeScript?
You need to transform FooBarAction into a discriminated union. At the moment your version of FooBarAction is not very strict, while type must be one of "FOO" | "BAR" and data must be one of FooBarTypeMap[FooBarTypes] = FooInterface | BarInterface there is no relation between the two. So this could be allowed:
let o : FooBarAction2<FooBarTypes> = {
type: "BAR",
data: {} as FooInterface
}
The discriminated union version would look like this:
export type FooBarAction = {
type: "FOO";
data: FooInterface;
} | {
type: "BAR";
data: BarInterface;
}
const doSomthingBasedOnType = (action: FooBarAction): void => {
switch (action.type) {
case "FOO":
FooAction(action);
}
};
// We use extract to get a specific type from the union
const FooAction = (action: Extract<FooBarAction, { type: "FOO" }>): void => {
//do something with action.data
};
You can also create a union from a union of types using the distributive behavior of conditional types:
interface FooInterface { foo: number}
interface BarInterface { bar: number}
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;
const doSomthingBasedOnType = (action: FooBarAction<FooBarTypes>): void => {
switch (action.type) {
case "FOO":
FooAction(action);
}
};
const FooAction = (action: FooBarAction<"FOO">): void => {
//do something with action.data
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With