Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid typescript casting inside a switch

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?

like image 444
MrMamen Avatar asked Jul 15 '26 04:07

MrMamen


1 Answers

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
};
like image 164
Titian Cernicova-Dragomir Avatar answered Jul 17 '26 18:07

Titian Cernicova-Dragomir