Creating a discriminated union for a typescript function












1















This is a continuation of an issue resolved here: Avoid typescript casting inside a switch
Using that I have set up types like this:



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
});


Changing either input or return value to any works, but obviously I would like to avoid that. I tried creating a AllFooBarInterfaces which FooInterface and BarInterface extends like this:



// 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,
}


While I can do changes in the above definition of interfaces and types, I still need to support the case asked in the original question, which is included below for easy access.



const doSomthingBasedOnType = (action: FooBarAction<FooBarTypes>): void => {
switch (action.type) {
case "FOO":
FooAction(action);
}
};

const FooAction = (action: FooBarAction<"FOO">): void => {
//do something with action.data
};









share|improve this question



























    1















    This is a continuation of an issue resolved here: Avoid typescript casting inside a switch
    Using that I have set up types like this:



    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
    });


    Changing either input or return value to any works, but obviously I would like to avoid that. I tried creating a AllFooBarInterfaces which FooInterface and BarInterface extends like this:



    // 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,
    }


    While I can do changes in the above definition of interfaces and types, I still need to support the case asked in the original question, which is included below for easy access.



    const doSomthingBasedOnType = (action: FooBarAction<FooBarTypes>): void => {
    switch (action.type) {
    case "FOO":
    FooAction(action);
    }
    };

    const FooAction = (action: FooBarAction<"FOO">): void => {
    //do something with action.data
    };









    share|improve this question

























      1












      1








      1








      This is a continuation of an issue resolved here: Avoid typescript casting inside a switch
      Using that I have set up types like this:



      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
      });


      Changing either input or return value to any works, but obviously I would like to avoid that. I tried creating a AllFooBarInterfaces which FooInterface and BarInterface extends like this:



      // 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,
      }


      While I can do changes in the above definition of interfaces and types, I still need to support the case asked in the original question, which is included below for easy access.



      const doSomthingBasedOnType = (action: FooBarAction<FooBarTypes>): void => {
      switch (action.type) {
      case "FOO":
      FooAction(action);
      }
      };

      const FooAction = (action: FooBarAction<"FOO">): void => {
      //do something with action.data
      };









      share|improve this question














      This is a continuation of an issue resolved here: Avoid typescript casting inside a switch
      Using that I have set up types like this:



      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
      });


      Changing either input or return value to any works, but obviously I would like to avoid that. I tried creating a AllFooBarInterfaces which FooInterface and BarInterface extends like this:



      // 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,
      }


      While I can do changes in the above definition of interfaces and types, I still need to support the case asked in the original question, which is included below for easy access.



      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






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 22 '18 at 10:27









      MrMamenMrMamen

      508




      508
























          1 Answer
          1






          active

          oldest

          votes


















          1














          You implementation will not work because Typescript does not allow the assignment of values to places where a type with unresolved generic parameters is expected. The best solution, to preserve call site behavior is to add an overload that has the generic type parameter, and an sperate implementation signature, that is a little less type safe but that allows us to actually implement the function:



          function createFooBarAction <T extends FooBarTypes>(fooBarData: FooBarTypeMap[T]): FooBarAction<T>
          function createFooBarAction (fooBarData: FooBarTypeMap[FooBarTypes]): FooBarAction<any> {
          return {
          type: fooBarData.type,
          data: fooBarData
          };
          }


          Note the use of any in the return type. This is unfortunately required. Returning
          FooBarAction<FooBarTypes> will not work since the returned object will be typed as { type: FooBarTypes; data: FooInterface | BarInterface; } while FooBarAction<FooBarTypes> is resolved to { type: "FOO"; data: FooInterface; } | { type: "BAR"; data: BarInterface; }.



          We could use a switch in this case as well to convince the compiler that out types are correct, but since each branch of the switch will have the same code, it seems like overkill :



          function createFooBarAction <T extends FooBarTypes>(fooBarData: FooBarTypeMap[T]): FooBarAction<T>
          function createFooBarAction (fooBarData: FooBarTypeMap[FooBarTypes]): FooBarAction<FooBarTypes> {
          switch (fooBarData.type) {
          case "FOO": return { type:fooBarData.type, data: fooBarData }
          case "BAR": return { type:fooBarData.type, data: fooBarData }
          }
          }





          share|improve this answer
























          • Wow. I was trying to do something that seems to be impossible. Anyway, thanks a lot for your help. You seem to say that FoobarAction<FooBarTypes> resolves to two different things. I'm guessing the latter should be FoobarAction<any>. Is there a case where the any could actually go wrong?

            – MrMamen
            Nov 22 '18 at 19:14











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53428841%2fcreating-a-discriminated-union-for-a-typescript-function%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          You implementation will not work because Typescript does not allow the assignment of values to places where a type with unresolved generic parameters is expected. The best solution, to preserve call site behavior is to add an overload that has the generic type parameter, and an sperate implementation signature, that is a little less type safe but that allows us to actually implement the function:



          function createFooBarAction <T extends FooBarTypes>(fooBarData: FooBarTypeMap[T]): FooBarAction<T>
          function createFooBarAction (fooBarData: FooBarTypeMap[FooBarTypes]): FooBarAction<any> {
          return {
          type: fooBarData.type,
          data: fooBarData
          };
          }


          Note the use of any in the return type. This is unfortunately required. Returning
          FooBarAction<FooBarTypes> will not work since the returned object will be typed as { type: FooBarTypes; data: FooInterface | BarInterface; } while FooBarAction<FooBarTypes> is resolved to { type: "FOO"; data: FooInterface; } | { type: "BAR"; data: BarInterface; }.



          We could use a switch in this case as well to convince the compiler that out types are correct, but since each branch of the switch will have the same code, it seems like overkill :



          function createFooBarAction <T extends FooBarTypes>(fooBarData: FooBarTypeMap[T]): FooBarAction<T>
          function createFooBarAction (fooBarData: FooBarTypeMap[FooBarTypes]): FooBarAction<FooBarTypes> {
          switch (fooBarData.type) {
          case "FOO": return { type:fooBarData.type, data: fooBarData }
          case "BAR": return { type:fooBarData.type, data: fooBarData }
          }
          }





          share|improve this answer
























          • Wow. I was trying to do something that seems to be impossible. Anyway, thanks a lot for your help. You seem to say that FoobarAction<FooBarTypes> resolves to two different things. I'm guessing the latter should be FoobarAction<any>. Is there a case where the any could actually go wrong?

            – MrMamen
            Nov 22 '18 at 19:14
















          1














          You implementation will not work because Typescript does not allow the assignment of values to places where a type with unresolved generic parameters is expected. The best solution, to preserve call site behavior is to add an overload that has the generic type parameter, and an sperate implementation signature, that is a little less type safe but that allows us to actually implement the function:



          function createFooBarAction <T extends FooBarTypes>(fooBarData: FooBarTypeMap[T]): FooBarAction<T>
          function createFooBarAction (fooBarData: FooBarTypeMap[FooBarTypes]): FooBarAction<any> {
          return {
          type: fooBarData.type,
          data: fooBarData
          };
          }


          Note the use of any in the return type. This is unfortunately required. Returning
          FooBarAction<FooBarTypes> will not work since the returned object will be typed as { type: FooBarTypes; data: FooInterface | BarInterface; } while FooBarAction<FooBarTypes> is resolved to { type: "FOO"; data: FooInterface; } | { type: "BAR"; data: BarInterface; }.



          We could use a switch in this case as well to convince the compiler that out types are correct, but since each branch of the switch will have the same code, it seems like overkill :



          function createFooBarAction <T extends FooBarTypes>(fooBarData: FooBarTypeMap[T]): FooBarAction<T>
          function createFooBarAction (fooBarData: FooBarTypeMap[FooBarTypes]): FooBarAction<FooBarTypes> {
          switch (fooBarData.type) {
          case "FOO": return { type:fooBarData.type, data: fooBarData }
          case "BAR": return { type:fooBarData.type, data: fooBarData }
          }
          }





          share|improve this answer
























          • Wow. I was trying to do something that seems to be impossible. Anyway, thanks a lot for your help. You seem to say that FoobarAction<FooBarTypes> resolves to two different things. I'm guessing the latter should be FoobarAction<any>. Is there a case where the any could actually go wrong?

            – MrMamen
            Nov 22 '18 at 19:14














          1












          1








          1







          You implementation will not work because Typescript does not allow the assignment of values to places where a type with unresolved generic parameters is expected. The best solution, to preserve call site behavior is to add an overload that has the generic type parameter, and an sperate implementation signature, that is a little less type safe but that allows us to actually implement the function:



          function createFooBarAction <T extends FooBarTypes>(fooBarData: FooBarTypeMap[T]): FooBarAction<T>
          function createFooBarAction (fooBarData: FooBarTypeMap[FooBarTypes]): FooBarAction<any> {
          return {
          type: fooBarData.type,
          data: fooBarData
          };
          }


          Note the use of any in the return type. This is unfortunately required. Returning
          FooBarAction<FooBarTypes> will not work since the returned object will be typed as { type: FooBarTypes; data: FooInterface | BarInterface; } while FooBarAction<FooBarTypes> is resolved to { type: "FOO"; data: FooInterface; } | { type: "BAR"; data: BarInterface; }.



          We could use a switch in this case as well to convince the compiler that out types are correct, but since each branch of the switch will have the same code, it seems like overkill :



          function createFooBarAction <T extends FooBarTypes>(fooBarData: FooBarTypeMap[T]): FooBarAction<T>
          function createFooBarAction (fooBarData: FooBarTypeMap[FooBarTypes]): FooBarAction<FooBarTypes> {
          switch (fooBarData.type) {
          case "FOO": return { type:fooBarData.type, data: fooBarData }
          case "BAR": return { type:fooBarData.type, data: fooBarData }
          }
          }





          share|improve this answer













          You implementation will not work because Typescript does not allow the assignment of values to places where a type with unresolved generic parameters is expected. The best solution, to preserve call site behavior is to add an overload that has the generic type parameter, and an sperate implementation signature, that is a little less type safe but that allows us to actually implement the function:



          function createFooBarAction <T extends FooBarTypes>(fooBarData: FooBarTypeMap[T]): FooBarAction<T>
          function createFooBarAction (fooBarData: FooBarTypeMap[FooBarTypes]): FooBarAction<any> {
          return {
          type: fooBarData.type,
          data: fooBarData
          };
          }


          Note the use of any in the return type. This is unfortunately required. Returning
          FooBarAction<FooBarTypes> will not work since the returned object will be typed as { type: FooBarTypes; data: FooInterface | BarInterface; } while FooBarAction<FooBarTypes> is resolved to { type: "FOO"; data: FooInterface; } | { type: "BAR"; data: BarInterface; }.



          We could use a switch in this case as well to convince the compiler that out types are correct, but since each branch of the switch will have the same code, it seems like overkill :



          function createFooBarAction <T extends FooBarTypes>(fooBarData: FooBarTypeMap[T]): FooBarAction<T>
          function createFooBarAction (fooBarData: FooBarTypeMap[FooBarTypes]): FooBarAction<FooBarTypes> {
          switch (fooBarData.type) {
          case "FOO": return { type:fooBarData.type, data: fooBarData }
          case "BAR": return { type:fooBarData.type, data: fooBarData }
          }
          }






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 22 '18 at 14:05









          Titian Cernicova-DragomirTitian Cernicova-Dragomir

          59.7k33553




          59.7k33553













          • Wow. I was trying to do something that seems to be impossible. Anyway, thanks a lot for your help. You seem to say that FoobarAction<FooBarTypes> resolves to two different things. I'm guessing the latter should be FoobarAction<any>. Is there a case where the any could actually go wrong?

            – MrMamen
            Nov 22 '18 at 19:14



















          • Wow. I was trying to do something that seems to be impossible. Anyway, thanks a lot for your help. You seem to say that FoobarAction<FooBarTypes> resolves to two different things. I'm guessing the latter should be FoobarAction<any>. Is there a case where the any could actually go wrong?

            – MrMamen
            Nov 22 '18 at 19:14

















          Wow. I was trying to do something that seems to be impossible. Anyway, thanks a lot for your help. You seem to say that FoobarAction<FooBarTypes> resolves to two different things. I'm guessing the latter should be FoobarAction<any>. Is there a case where the any could actually go wrong?

          – MrMamen
          Nov 22 '18 at 19:14





          Wow. I was trying to do something that seems to be impossible. Anyway, thanks a lot for your help. You seem to say that FoobarAction<FooBarTypes> resolves to two different things. I'm guessing the latter should be FoobarAction<any>. Is there a case where the any could actually go wrong?

          – MrMamen
          Nov 22 '18 at 19:14


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53428841%2fcreating-a-discriminated-union-for-a-typescript-function%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          404 Error Contact Form 7 ajax form submitting

          How to know if a Active Directory user can login interactively

          TypeError: fit_transform() missing 1 required positional argument: 'X'