Generic type of extended interface not inferred












2















In the following example Typescript can infer the type of T in method foo from the parameter passed to it in bar, but it doesn't infer the type of R, which it feels like it should - given that it knows the type of T and also that T extends I<R>



interface I<T> {
}

class A implements I<string> {

}

function foo<T extends I<R>, R>(bar: T): R {
return;
}

foo(new A());


Is there another way to do this?










share|improve this question



























    2















    In the following example Typescript can infer the type of T in method foo from the parameter passed to it in bar, but it doesn't infer the type of R, which it feels like it should - given that it knows the type of T and also that T extends I<R>



    interface I<T> {
    }

    class A implements I<string> {

    }

    function foo<T extends I<R>, R>(bar: T): R {
    return;
    }

    foo(new A());


    Is there another way to do this?










    share|improve this question

























      2












      2








      2








      In the following example Typescript can infer the type of T in method foo from the parameter passed to it in bar, but it doesn't infer the type of R, which it feels like it should - given that it knows the type of T and also that T extends I<R>



      interface I<T> {
      }

      class A implements I<string> {

      }

      function foo<T extends I<R>, R>(bar: T): R {
      return;
      }

      foo(new A());


      Is there another way to do this?










      share|improve this question














      In the following example Typescript can infer the type of T in method foo from the parameter passed to it in bar, but it doesn't infer the type of R, which it feels like it should - given that it knows the type of T and also that T extends I<R>



      interface I<T> {
      }

      class A implements I<string> {

      }

      function foo<T extends I<R>, R>(bar: T): R {
      return;
      }

      foo(new A());


      Is there another way to do this?







      typescript generics types type-inference






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 23 '18 at 14:01









      IBOED2IBOED2

      54116




      54116
























          1 Answer
          1






          active

          oldest

          votes


















          1














          The first problem is that your interface is empty, typescript uses structural typing so if your generic interface will not use it's type parameter it won't matter much that it has it. For example this works:



          interface I<T> { }
          declare let foo: I<string>
          declare let bar: I<number>
          // Same structure ({}), assignment works
          foo = bar
          bar = foo


          Event if we add a field, Typescript will still not infer the R type parameter, it just doesn't try to extract it from T. Your best option is to use a conditional type and extract the generic type parameter where you need it:



          interface I<T> {
          value :T
          }

          class A implements I<string> {
          value! :string
          }

          type ExtractFromI<T extends I<unknown>> = T extends I<infer U> ? U : never;
          function foo<T extends I<unknown>>(bar: T): ExtractFromI<T>{
          return bar.value as ExtractFromI<T>; // Generic type with unresolved type parameters, we need a type assertion to convince the compiler this is ok
          }
          var r = foo(new A()); // string





          share|improve this answer
























          • That's super cool thanks, follow up question, is it possible to make this ExtractFrom mapped type generic? So that it can extract from any interface rather than specifically I?

            – IBOED2
            Nov 23 '18 at 14:52











          • @IBOED2 unfortunately no, you will need a dedicated conditional type tailored for each generic type you want to extract parameters from.

            – Titian Cernicova-Dragomir
            Nov 23 '18 at 14:53











          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%2f53448100%2fgeneric-type-of-extended-interface-not-inferred%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














          The first problem is that your interface is empty, typescript uses structural typing so if your generic interface will not use it's type parameter it won't matter much that it has it. For example this works:



          interface I<T> { }
          declare let foo: I<string>
          declare let bar: I<number>
          // Same structure ({}), assignment works
          foo = bar
          bar = foo


          Event if we add a field, Typescript will still not infer the R type parameter, it just doesn't try to extract it from T. Your best option is to use a conditional type and extract the generic type parameter where you need it:



          interface I<T> {
          value :T
          }

          class A implements I<string> {
          value! :string
          }

          type ExtractFromI<T extends I<unknown>> = T extends I<infer U> ? U : never;
          function foo<T extends I<unknown>>(bar: T): ExtractFromI<T>{
          return bar.value as ExtractFromI<T>; // Generic type with unresolved type parameters, we need a type assertion to convince the compiler this is ok
          }
          var r = foo(new A()); // string





          share|improve this answer
























          • That's super cool thanks, follow up question, is it possible to make this ExtractFrom mapped type generic? So that it can extract from any interface rather than specifically I?

            – IBOED2
            Nov 23 '18 at 14:52











          • @IBOED2 unfortunately no, you will need a dedicated conditional type tailored for each generic type you want to extract parameters from.

            – Titian Cernicova-Dragomir
            Nov 23 '18 at 14:53
















          1














          The first problem is that your interface is empty, typescript uses structural typing so if your generic interface will not use it's type parameter it won't matter much that it has it. For example this works:



          interface I<T> { }
          declare let foo: I<string>
          declare let bar: I<number>
          // Same structure ({}), assignment works
          foo = bar
          bar = foo


          Event if we add a field, Typescript will still not infer the R type parameter, it just doesn't try to extract it from T. Your best option is to use a conditional type and extract the generic type parameter where you need it:



          interface I<T> {
          value :T
          }

          class A implements I<string> {
          value! :string
          }

          type ExtractFromI<T extends I<unknown>> = T extends I<infer U> ? U : never;
          function foo<T extends I<unknown>>(bar: T): ExtractFromI<T>{
          return bar.value as ExtractFromI<T>; // Generic type with unresolved type parameters, we need a type assertion to convince the compiler this is ok
          }
          var r = foo(new A()); // string





          share|improve this answer
























          • That's super cool thanks, follow up question, is it possible to make this ExtractFrom mapped type generic? So that it can extract from any interface rather than specifically I?

            – IBOED2
            Nov 23 '18 at 14:52











          • @IBOED2 unfortunately no, you will need a dedicated conditional type tailored for each generic type you want to extract parameters from.

            – Titian Cernicova-Dragomir
            Nov 23 '18 at 14:53














          1












          1








          1







          The first problem is that your interface is empty, typescript uses structural typing so if your generic interface will not use it's type parameter it won't matter much that it has it. For example this works:



          interface I<T> { }
          declare let foo: I<string>
          declare let bar: I<number>
          // Same structure ({}), assignment works
          foo = bar
          bar = foo


          Event if we add a field, Typescript will still not infer the R type parameter, it just doesn't try to extract it from T. Your best option is to use a conditional type and extract the generic type parameter where you need it:



          interface I<T> {
          value :T
          }

          class A implements I<string> {
          value! :string
          }

          type ExtractFromI<T extends I<unknown>> = T extends I<infer U> ? U : never;
          function foo<T extends I<unknown>>(bar: T): ExtractFromI<T>{
          return bar.value as ExtractFromI<T>; // Generic type with unresolved type parameters, we need a type assertion to convince the compiler this is ok
          }
          var r = foo(new A()); // string





          share|improve this answer













          The first problem is that your interface is empty, typescript uses structural typing so if your generic interface will not use it's type parameter it won't matter much that it has it. For example this works:



          interface I<T> { }
          declare let foo: I<string>
          declare let bar: I<number>
          // Same structure ({}), assignment works
          foo = bar
          bar = foo


          Event if we add a field, Typescript will still not infer the R type parameter, it just doesn't try to extract it from T. Your best option is to use a conditional type and extract the generic type parameter where you need it:



          interface I<T> {
          value :T
          }

          class A implements I<string> {
          value! :string
          }

          type ExtractFromI<T extends I<unknown>> = T extends I<infer U> ? U : never;
          function foo<T extends I<unknown>>(bar: T): ExtractFromI<T>{
          return bar.value as ExtractFromI<T>; // Generic type with unresolved type parameters, we need a type assertion to convince the compiler this is ok
          }
          var r = foo(new A()); // string






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 23 '18 at 14:09









          Titian Cernicova-DragomirTitian Cernicova-Dragomir

          59.2k33553




          59.2k33553













          • That's super cool thanks, follow up question, is it possible to make this ExtractFrom mapped type generic? So that it can extract from any interface rather than specifically I?

            – IBOED2
            Nov 23 '18 at 14:52











          • @IBOED2 unfortunately no, you will need a dedicated conditional type tailored for each generic type you want to extract parameters from.

            – Titian Cernicova-Dragomir
            Nov 23 '18 at 14:53



















          • That's super cool thanks, follow up question, is it possible to make this ExtractFrom mapped type generic? So that it can extract from any interface rather than specifically I?

            – IBOED2
            Nov 23 '18 at 14:52











          • @IBOED2 unfortunately no, you will need a dedicated conditional type tailored for each generic type you want to extract parameters from.

            – Titian Cernicova-Dragomir
            Nov 23 '18 at 14:53

















          That's super cool thanks, follow up question, is it possible to make this ExtractFrom mapped type generic? So that it can extract from any interface rather than specifically I?

          – IBOED2
          Nov 23 '18 at 14:52





          That's super cool thanks, follow up question, is it possible to make this ExtractFrom mapped type generic? So that it can extract from any interface rather than specifically I?

          – IBOED2
          Nov 23 '18 at 14:52













          @IBOED2 unfortunately no, you will need a dedicated conditional type tailored for each generic type you want to extract parameters from.

          – Titian Cernicova-Dragomir
          Nov 23 '18 at 14:53





          @IBOED2 unfortunately no, you will need a dedicated conditional type tailored for each generic type you want to extract parameters from.

          – Titian Cernicova-Dragomir
          Nov 23 '18 at 14:53


















          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%2f53448100%2fgeneric-type-of-extended-interface-not-inferred%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

          Berounka

          Sphinx de Gizeh

          Different font size/position of beamer's navigation symbols template's content depending on regular/plain...