Typescript infer Generic types from Implementation











up vote
3
down vote

favorite












So I am working on a react-native project.
I was hoping if one could infer Generic types from implementation.



type itemType<T> = { item: T };

const someItem = {
item: 'Some String'
};

type someItemType = typeof someItem;
// So Here someItemType will be {item: string}, i want it to be itemType<string> and
// in this example i have implemented itemType but in real use case i want to infer
//it from the actual implementation









share|improve this question


























    up vote
    3
    down vote

    favorite












    So I am working on a react-native project.
    I was hoping if one could infer Generic types from implementation.



    type itemType<T> = { item: T };

    const someItem = {
    item: 'Some String'
    };

    type someItemType = typeof someItem;
    // So Here someItemType will be {item: string}, i want it to be itemType<string> and
    // in this example i have implemented itemType but in real use case i want to infer
    //it from the actual implementation









    share|improve this question
























      up vote
      3
      down vote

      favorite









      up vote
      3
      down vote

      favorite











      So I am working on a react-native project.
      I was hoping if one could infer Generic types from implementation.



      type itemType<T> = { item: T };

      const someItem = {
      item: 'Some String'
      };

      type someItemType = typeof someItem;
      // So Here someItemType will be {item: string}, i want it to be itemType<string> and
      // in this example i have implemented itemType but in real use case i want to infer
      //it from the actual implementation









      share|improve this question













      So I am working on a react-native project.
      I was hoping if one could infer Generic types from implementation.



      type itemType<T> = { item: T };

      const someItem = {
      item: 'Some String'
      };

      type someItemType = typeof someItem;
      // So Here someItemType will be {item: string}, i want it to be itemType<string> and
      // in this example i have implemented itemType but in real use case i want to infer
      //it from the actual implementation






      typescript typescript-typings






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 22 at 8:31









      Amol Gupta

      648




      648
























          2 Answers
          2






          active

          oldest

          votes

















          up vote
          2
          down vote



          accepted










          Partial inference on variables is not supported at present in typescript. Your only option is to use the inference behavior of function:



          type itemType<T> = { item: T };
          const createItemType = <T>(o: itemType<T>) => o;

          const someItem = createItemType({ //someItem is typed as itemType<string>
          item: 'Some String'
          })


          Just one note, it might not matter that in your original example someItem is typed as {item: string}, it will still be assignable to itemType<string> because typescript uses structural compatibility to determine assignability. So if the structure is compatible all is ok:



          type itemType<T> = { item: T };

          const someItem ={
          item: 'Some String'
          }
          const someOtherItem: itemType<string> = someItem // ok





          share|improve this answer























          • In this case, I wouldn't write extra runtime code as there is no benefit to making the names match outside of a nominal type system.
            – Fenton
            Nov 22 at 8:44










          • @Fenton agreed, that is why I pointed out it does not much matter what the actual type if someItem is, al least with regard to future assignability to itemType<string>. There might be benefit in ensuring the object conforms to the itemType<T> interface at declaration site, rather than on future usage, I'd expect the perf impact of the identity function used to not be too high in most scenarios.
            – Titian Cernicova-Dragomir
            Nov 22 at 8:46










          • I famously don't worry about performance impact - I worry about having to go back and change the program in six months :)
            – Fenton
            Nov 22 at 8:48










          • @Fenton I must admit, while I do worry about that I have used such functions to help with inference all in one line const someItem = (<T>(o: itemType<T>) => o)({ item: 'Some String' }) I will understand then in 6 months.. not sure anybody else understands them right now :)
            – Titian Cernicova-Dragomir
            Nov 22 at 8:51










          • I have some code that looks a bit like this in C#. I think if you flash it up for half a second and ask people to guess what they saw, and they answer "A Regular Expression" it's time to refactor.
            – Fenton
            Nov 22 at 8:54


















          up vote
          2
          down vote













          It doesn't matter whether the type is defined as { item: string } or itemType<string> as TypeScript uses structural typing. That means the two are the same, because they have identical structures.



          For example, you can assign values of either type to each other type:



          type itemType<T> = { item: T };

          const someItem = {
          item: 'Some String'
          };

          type someItemType = typeof someItem;

          const a: itemType<string> = { item: 'exmaple a' };
          const b: someItemType = { item: 'exmaple b' };

          let c: itemType<string>;

          c = a;
          c = b;

          let d: someItemType;

          d = a;
          d = b;





          share|improve this answer





















          • So the thing is i do not want to write type itemType<T> = { item: T }; i want to infer it from the implementation.
            – Amol Gupta
            Nov 22 at 8:52










          • That way if i update the original object my types are automatically updated.
            – Amol Gupta
            Nov 22 at 8:53










          • If you update the original object, it may no longer be an itemType<T>.
            – Fenton
            Nov 22 at 9:08











          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',
          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%2f53426728%2ftypescript-infer-generic-types-from-implementation%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          2 Answers
          2






          active

          oldest

          votes








          2 Answers
          2






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          2
          down vote



          accepted










          Partial inference on variables is not supported at present in typescript. Your only option is to use the inference behavior of function:



          type itemType<T> = { item: T };
          const createItemType = <T>(o: itemType<T>) => o;

          const someItem = createItemType({ //someItem is typed as itemType<string>
          item: 'Some String'
          })


          Just one note, it might not matter that in your original example someItem is typed as {item: string}, it will still be assignable to itemType<string> because typescript uses structural compatibility to determine assignability. So if the structure is compatible all is ok:



          type itemType<T> = { item: T };

          const someItem ={
          item: 'Some String'
          }
          const someOtherItem: itemType<string> = someItem // ok





          share|improve this answer























          • In this case, I wouldn't write extra runtime code as there is no benefit to making the names match outside of a nominal type system.
            – Fenton
            Nov 22 at 8:44










          • @Fenton agreed, that is why I pointed out it does not much matter what the actual type if someItem is, al least with regard to future assignability to itemType<string>. There might be benefit in ensuring the object conforms to the itemType<T> interface at declaration site, rather than on future usage, I'd expect the perf impact of the identity function used to not be too high in most scenarios.
            – Titian Cernicova-Dragomir
            Nov 22 at 8:46










          • I famously don't worry about performance impact - I worry about having to go back and change the program in six months :)
            – Fenton
            Nov 22 at 8:48










          • @Fenton I must admit, while I do worry about that I have used such functions to help with inference all in one line const someItem = (<T>(o: itemType<T>) => o)({ item: 'Some String' }) I will understand then in 6 months.. not sure anybody else understands them right now :)
            – Titian Cernicova-Dragomir
            Nov 22 at 8:51










          • I have some code that looks a bit like this in C#. I think if you flash it up for half a second and ask people to guess what they saw, and they answer "A Regular Expression" it's time to refactor.
            – Fenton
            Nov 22 at 8:54















          up vote
          2
          down vote



          accepted










          Partial inference on variables is not supported at present in typescript. Your only option is to use the inference behavior of function:



          type itemType<T> = { item: T };
          const createItemType = <T>(o: itemType<T>) => o;

          const someItem = createItemType({ //someItem is typed as itemType<string>
          item: 'Some String'
          })


          Just one note, it might not matter that in your original example someItem is typed as {item: string}, it will still be assignable to itemType<string> because typescript uses structural compatibility to determine assignability. So if the structure is compatible all is ok:



          type itemType<T> = { item: T };

          const someItem ={
          item: 'Some String'
          }
          const someOtherItem: itemType<string> = someItem // ok





          share|improve this answer























          • In this case, I wouldn't write extra runtime code as there is no benefit to making the names match outside of a nominal type system.
            – Fenton
            Nov 22 at 8:44










          • @Fenton agreed, that is why I pointed out it does not much matter what the actual type if someItem is, al least with regard to future assignability to itemType<string>. There might be benefit in ensuring the object conforms to the itemType<T> interface at declaration site, rather than on future usage, I'd expect the perf impact of the identity function used to not be too high in most scenarios.
            – Titian Cernicova-Dragomir
            Nov 22 at 8:46










          • I famously don't worry about performance impact - I worry about having to go back and change the program in six months :)
            – Fenton
            Nov 22 at 8:48










          • @Fenton I must admit, while I do worry about that I have used such functions to help with inference all in one line const someItem = (<T>(o: itemType<T>) => o)({ item: 'Some String' }) I will understand then in 6 months.. not sure anybody else understands them right now :)
            – Titian Cernicova-Dragomir
            Nov 22 at 8:51










          • I have some code that looks a bit like this in C#. I think if you flash it up for half a second and ask people to guess what they saw, and they answer "A Regular Expression" it's time to refactor.
            – Fenton
            Nov 22 at 8:54













          up vote
          2
          down vote



          accepted







          up vote
          2
          down vote



          accepted






          Partial inference on variables is not supported at present in typescript. Your only option is to use the inference behavior of function:



          type itemType<T> = { item: T };
          const createItemType = <T>(o: itemType<T>) => o;

          const someItem = createItemType({ //someItem is typed as itemType<string>
          item: 'Some String'
          })


          Just one note, it might not matter that in your original example someItem is typed as {item: string}, it will still be assignable to itemType<string> because typescript uses structural compatibility to determine assignability. So if the structure is compatible all is ok:



          type itemType<T> = { item: T };

          const someItem ={
          item: 'Some String'
          }
          const someOtherItem: itemType<string> = someItem // ok





          share|improve this answer














          Partial inference on variables is not supported at present in typescript. Your only option is to use the inference behavior of function:



          type itemType<T> = { item: T };
          const createItemType = <T>(o: itemType<T>) => o;

          const someItem = createItemType({ //someItem is typed as itemType<string>
          item: 'Some String'
          })


          Just one note, it might not matter that in your original example someItem is typed as {item: string}, it will still be assignable to itemType<string> because typescript uses structural compatibility to determine assignability. So if the structure is compatible all is ok:



          type itemType<T> = { item: T };

          const someItem ={
          item: 'Some String'
          }
          const someOtherItem: itemType<string> = someItem // ok






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 22 at 8:47

























          answered Nov 22 at 8:43









          Titian Cernicova-Dragomir

          54.6k33351




          54.6k33351












          • In this case, I wouldn't write extra runtime code as there is no benefit to making the names match outside of a nominal type system.
            – Fenton
            Nov 22 at 8:44










          • @Fenton agreed, that is why I pointed out it does not much matter what the actual type if someItem is, al least with regard to future assignability to itemType<string>. There might be benefit in ensuring the object conforms to the itemType<T> interface at declaration site, rather than on future usage, I'd expect the perf impact of the identity function used to not be too high in most scenarios.
            – Titian Cernicova-Dragomir
            Nov 22 at 8:46










          • I famously don't worry about performance impact - I worry about having to go back and change the program in six months :)
            – Fenton
            Nov 22 at 8:48










          • @Fenton I must admit, while I do worry about that I have used such functions to help with inference all in one line const someItem = (<T>(o: itemType<T>) => o)({ item: 'Some String' }) I will understand then in 6 months.. not sure anybody else understands them right now :)
            – Titian Cernicova-Dragomir
            Nov 22 at 8:51










          • I have some code that looks a bit like this in C#. I think if you flash it up for half a second and ask people to guess what they saw, and they answer "A Regular Expression" it's time to refactor.
            – Fenton
            Nov 22 at 8:54


















          • In this case, I wouldn't write extra runtime code as there is no benefit to making the names match outside of a nominal type system.
            – Fenton
            Nov 22 at 8:44










          • @Fenton agreed, that is why I pointed out it does not much matter what the actual type if someItem is, al least with regard to future assignability to itemType<string>. There might be benefit in ensuring the object conforms to the itemType<T> interface at declaration site, rather than on future usage, I'd expect the perf impact of the identity function used to not be too high in most scenarios.
            – Titian Cernicova-Dragomir
            Nov 22 at 8:46










          • I famously don't worry about performance impact - I worry about having to go back and change the program in six months :)
            – Fenton
            Nov 22 at 8:48










          • @Fenton I must admit, while I do worry about that I have used such functions to help with inference all in one line const someItem = (<T>(o: itemType<T>) => o)({ item: 'Some String' }) I will understand then in 6 months.. not sure anybody else understands them right now :)
            – Titian Cernicova-Dragomir
            Nov 22 at 8:51










          • I have some code that looks a bit like this in C#. I think if you flash it up for half a second and ask people to guess what they saw, and they answer "A Regular Expression" it's time to refactor.
            – Fenton
            Nov 22 at 8:54
















          In this case, I wouldn't write extra runtime code as there is no benefit to making the names match outside of a nominal type system.
          – Fenton
          Nov 22 at 8:44




          In this case, I wouldn't write extra runtime code as there is no benefit to making the names match outside of a nominal type system.
          – Fenton
          Nov 22 at 8:44












          @Fenton agreed, that is why I pointed out it does not much matter what the actual type if someItem is, al least with regard to future assignability to itemType<string>. There might be benefit in ensuring the object conforms to the itemType<T> interface at declaration site, rather than on future usage, I'd expect the perf impact of the identity function used to not be too high in most scenarios.
          – Titian Cernicova-Dragomir
          Nov 22 at 8:46




          @Fenton agreed, that is why I pointed out it does not much matter what the actual type if someItem is, al least with regard to future assignability to itemType<string>. There might be benefit in ensuring the object conforms to the itemType<T> interface at declaration site, rather than on future usage, I'd expect the perf impact of the identity function used to not be too high in most scenarios.
          – Titian Cernicova-Dragomir
          Nov 22 at 8:46












          I famously don't worry about performance impact - I worry about having to go back and change the program in six months :)
          – Fenton
          Nov 22 at 8:48




          I famously don't worry about performance impact - I worry about having to go back and change the program in six months :)
          – Fenton
          Nov 22 at 8:48












          @Fenton I must admit, while I do worry about that I have used such functions to help with inference all in one line const someItem = (<T>(o: itemType<T>) => o)({ item: 'Some String' }) I will understand then in 6 months.. not sure anybody else understands them right now :)
          – Titian Cernicova-Dragomir
          Nov 22 at 8:51




          @Fenton I must admit, while I do worry about that I have used such functions to help with inference all in one line const someItem = (<T>(o: itemType<T>) => o)({ item: 'Some String' }) I will understand then in 6 months.. not sure anybody else understands them right now :)
          – Titian Cernicova-Dragomir
          Nov 22 at 8:51












          I have some code that looks a bit like this in C#. I think if you flash it up for half a second and ask people to guess what they saw, and they answer "A Regular Expression" it's time to refactor.
          – Fenton
          Nov 22 at 8:54




          I have some code that looks a bit like this in C#. I think if you flash it up for half a second and ask people to guess what they saw, and they answer "A Regular Expression" it's time to refactor.
          – Fenton
          Nov 22 at 8:54












          up vote
          2
          down vote













          It doesn't matter whether the type is defined as { item: string } or itemType<string> as TypeScript uses structural typing. That means the two are the same, because they have identical structures.



          For example, you can assign values of either type to each other type:



          type itemType<T> = { item: T };

          const someItem = {
          item: 'Some String'
          };

          type someItemType = typeof someItem;

          const a: itemType<string> = { item: 'exmaple a' };
          const b: someItemType = { item: 'exmaple b' };

          let c: itemType<string>;

          c = a;
          c = b;

          let d: someItemType;

          d = a;
          d = b;





          share|improve this answer





















          • So the thing is i do not want to write type itemType<T> = { item: T }; i want to infer it from the implementation.
            – Amol Gupta
            Nov 22 at 8:52










          • That way if i update the original object my types are automatically updated.
            – Amol Gupta
            Nov 22 at 8:53










          • If you update the original object, it may no longer be an itemType<T>.
            – Fenton
            Nov 22 at 9:08















          up vote
          2
          down vote













          It doesn't matter whether the type is defined as { item: string } or itemType<string> as TypeScript uses structural typing. That means the two are the same, because they have identical structures.



          For example, you can assign values of either type to each other type:



          type itemType<T> = { item: T };

          const someItem = {
          item: 'Some String'
          };

          type someItemType = typeof someItem;

          const a: itemType<string> = { item: 'exmaple a' };
          const b: someItemType = { item: 'exmaple b' };

          let c: itemType<string>;

          c = a;
          c = b;

          let d: someItemType;

          d = a;
          d = b;





          share|improve this answer





















          • So the thing is i do not want to write type itemType<T> = { item: T }; i want to infer it from the implementation.
            – Amol Gupta
            Nov 22 at 8:52










          • That way if i update the original object my types are automatically updated.
            – Amol Gupta
            Nov 22 at 8:53










          • If you update the original object, it may no longer be an itemType<T>.
            – Fenton
            Nov 22 at 9:08













          up vote
          2
          down vote










          up vote
          2
          down vote









          It doesn't matter whether the type is defined as { item: string } or itemType<string> as TypeScript uses structural typing. That means the two are the same, because they have identical structures.



          For example, you can assign values of either type to each other type:



          type itemType<T> = { item: T };

          const someItem = {
          item: 'Some String'
          };

          type someItemType = typeof someItem;

          const a: itemType<string> = { item: 'exmaple a' };
          const b: someItemType = { item: 'exmaple b' };

          let c: itemType<string>;

          c = a;
          c = b;

          let d: someItemType;

          d = a;
          d = b;





          share|improve this answer












          It doesn't matter whether the type is defined as { item: string } or itemType<string> as TypeScript uses structural typing. That means the two are the same, because they have identical structures.



          For example, you can assign values of either type to each other type:



          type itemType<T> = { item: T };

          const someItem = {
          item: 'Some String'
          };

          type someItemType = typeof someItem;

          const a: itemType<string> = { item: 'exmaple a' };
          const b: someItemType = { item: 'exmaple b' };

          let c: itemType<string>;

          c = a;
          c = b;

          let d: someItemType;

          d = a;
          d = b;






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 22 at 8:43









          Fenton

          150k42283308




          150k42283308












          • So the thing is i do not want to write type itemType<T> = { item: T }; i want to infer it from the implementation.
            – Amol Gupta
            Nov 22 at 8:52










          • That way if i update the original object my types are automatically updated.
            – Amol Gupta
            Nov 22 at 8:53










          • If you update the original object, it may no longer be an itemType<T>.
            – Fenton
            Nov 22 at 9:08


















          • So the thing is i do not want to write type itemType<T> = { item: T }; i want to infer it from the implementation.
            – Amol Gupta
            Nov 22 at 8:52










          • That way if i update the original object my types are automatically updated.
            – Amol Gupta
            Nov 22 at 8:53










          • If you update the original object, it may no longer be an itemType<T>.
            – Fenton
            Nov 22 at 9:08
















          So the thing is i do not want to write type itemType<T> = { item: T }; i want to infer it from the implementation.
          – Amol Gupta
          Nov 22 at 8:52




          So the thing is i do not want to write type itemType<T> = { item: T }; i want to infer it from the implementation.
          – Amol Gupta
          Nov 22 at 8:52












          That way if i update the original object my types are automatically updated.
          – Amol Gupta
          Nov 22 at 8:53




          That way if i update the original object my types are automatically updated.
          – Amol Gupta
          Nov 22 at 8:53












          If you update the original object, it may no longer be an itemType<T>.
          – Fenton
          Nov 22 at 9:08




          If you update the original object, it may no longer be an itemType<T>.
          – Fenton
          Nov 22 at 9:08


















          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.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • 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%2f53426728%2ftypescript-infer-generic-types-from-implementation%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

          A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks

          Calculate evaluation metrics using cross_val_predict sklearn

          Insert data from modal to MySQL (multiple modal on website)