Generic object return type is result of method chaining The Next CEO of Stack OverflowEnforcing the type of the indexed members of a Typescript object?Interface type check with TypescriptAre strongly-typed functions as parameters possible in TypeScript?How do I cast a JSON object to a typescript classShould I use typescript? or I can just use ES6?typescript getting error TS2304: cannot find name ' require'Generic Object type in typescriptDefault argument determining type of generic methodGetting the return type of a function which uses genericstypescript: make type that fits object literal values

When you upcast Blindness/Deafness, do all targets suffer the same effect?

I believe this to be a fraud - hired, then asked to cash check and send cash as Bitcoin

Make solar eclipses exceedingly rare, but still have new moons

I want to delete every two lines after 3rd lines in file contain very large number of lines :

Example of a Mathematician/Physicist whose Other Publications during their PhD eclipsed their PhD Thesis

Poetry, calligrams and TikZ/PStricks challenge

Is French Guiana a (hard) EU border?

Is wanting to ask what to write an indication that you need to change your story?

How to write a definition with variants?

Why did CATV standarize in 75 ohms and everyone else in 50?

Why don't programming languages automatically manage the synchronous/asynchronous problem?

The exact meaning of 'Mom made me a sandwich'

Which one is the true statement?

Writing differences on a blackboard

Is there always a complete, orthogonal set of unitary matrices?

Is there a way to save my career from absolute disaster?

What connection does MS Office have to Netscape Navigator?

Why is the US ranked as #45 in Press Freedom ratings, despite its extremely permissive free speech laws?

Do I need to write [sic] when a number is less than 10 but isn't written out?

Axiom Schema vs Axiom

Is the D&D universe the same as the Forgotten Realms universe?

What was the first Unix version to run on a microcomputer?

How to check if all elements of 1 list are in the *same quantity* and in any order, in the list2?

Easy to read palindrome checker



Generic object return type is result of method chaining



The Next CEO of Stack OverflowEnforcing the type of the indexed members of a Typescript object?Interface type check with TypescriptAre strongly-typed functions as parameters possible in TypeScript?How do I cast a JSON object to a typescript classShould I use typescript? or I can just use ES6?typescript getting error TS2304: cannot find name ' require'Generic Object type in typescriptDefault argument determining type of generic methodGetting the return type of a function which uses genericstypescript: make type that fits object literal values










2















I would like to do the following:



var result = loader
.add<number>(1)
.add<string>("hello")
.add<boolean>(true)
.run();


I would like to construct this theoretical loader object in such a way to have the TYPE of result be [number, string, boolean] without needing to manually declare it as such. Is there a way to do this in TypeScript?










share|improve this question


























    2















    I would like to do the following:



    var result = loader
    .add<number>(1)
    .add<string>("hello")
    .add<boolean>(true)
    .run();


    I would like to construct this theoretical loader object in such a way to have the TYPE of result be [number, string, boolean] without needing to manually declare it as such. Is there a way to do this in TypeScript?










    share|improve this question
























      2












      2








      2








      I would like to do the following:



      var result = loader
      .add<number>(1)
      .add<string>("hello")
      .add<boolean>(true)
      .run();


      I would like to construct this theoretical loader object in such a way to have the TYPE of result be [number, string, boolean] without needing to manually declare it as such. Is there a way to do this in TypeScript?










      share|improve this question














      I would like to do the following:



      var result = loader
      .add<number>(1)
      .add<string>("hello")
      .add<boolean>(true)
      .run();


      I would like to construct this theoretical loader object in such a way to have the TYPE of result be [number, string, boolean] without needing to manually declare it as such. Is there a way to do this in TypeScript?







      typescript typescript-generics






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 8 at 16:11









      TwitchBronBronTwitchBronBron

      1,3661128




      1,3661128






















          1 Answer
          1






          active

          oldest

          votes


















          1














          There is unfortunately no supported way in TypeScript to represent the type operation of appending a type onto the end of a tuple. I'll call this operation Push<T, V> where T is a tuple and V is any value type. There is a way to represent prepending a value onto the beginning of a tuple, which I'll call Cons<V, T>. That's because in TypeScript 3.0, a feature was introduced to treat tuples as the types of function parameters. We can also get Tail<T>, which pulls the first element (the head) off a tuple and returns the rest:



          type Cons<H, T extends any[]> = 
          ((h: H, ...t: T) => void) extends ((...r: infer R) => void) ? R : never;
          type Tail<T extends any[]> =
          ((...x: T) => void) extends ((h: infer A, ...t: infer R) => void) ? R : never;


          Given Cons and Tail, the natural representation of Push would be this recursive thing that doesn't work:



          type BadPush<T extends any[], V> = 
          T['length'] extends 0 ? [V] : Cons<T[0], BadPush<Tail<T>, V>>; // error, circular


          The idea there is that Push<[], V> should just be [V] (appending to an empty tuple is easy), and Push<[H, ...T], V> is Cons<H, Push<T, V>> (you hold onto the first element H and just push V onto the tail T... then prepend H back onto the result).



          While possible to trick the compiler into allowing such recursive types, it is not recommended. What I usually do instead is pick some maximum reasonable length of tuple I want to support modifying (say 9 or 10) and then unroll the circular definition:



          type Push<T extends any[], V> = T['length'] extends 0 ? [V] : Cons<T[0], Push1<Tail<T>, V>>
          type Push1<T extends any[], V> = T['length'] extends 0 ? [V] : Cons<T[0], Push2<Tail<T>, V>>
          type Push2<T extends any[], V> = T['length'] extends 0 ? [V] : Cons<T[0], Push3<Tail<T>, V>>
          type Push3<T extends any[], V> = T['length'] extends 0 ? [V] : Cons<T[0], Push4<Tail<T>, V>>
          type Push4<T extends any[], V> = T['length'] extends 0 ? [V] : Cons<T[0], Push5<Tail<T>, V>>
          type Push5<T extends any[], V> = T['length'] extends 0 ? [V] : Cons<T[0], Push6<Tail<T>, V>>
          type Push6<T extends any[], V> = T['length'] extends 0 ? [V] : Cons<T[0], Push7<Tail<T>, V>>
          type Push7<T extends any[], V> = T['length'] extends 0 ? [V] : Cons<T[0], Push8<Tail<T>, V>>
          type Push8<T extends any[], V> = T['length'] extends 0 ? [V] : Cons<T[0], Push9<Tail<T>, V>>
          type Push9<T extends any[], V> = T['length'] extends 0 ? [V] : Cons<T[0], PushX<Tail<T>, V>>
          type PushX<T extends any[], V> = Array<T[number] | V>; // give up


          Each line except PushX looks just like the recursive definition, and we intentionally cut things off at PushX by giving up and just forgetting about the order of elements (PushX<[1,2,3],4> is Array<1 | 2 | 3 | 4>).



          Now we can do this:



          type Test = Push<[1, 2, 3, 4, 5, 6, 7, 8], 9> // [1, 2, 3, 4, 5, 6, 7, 8, 9]



          Armed with Push, let's give a type to loader (leaving the implementation up to you):



          type Loader<T extends any[]> = 
          add<V>(x: V): Loader<Push<T, V>>;
          run(): T

          declare const loader: Loader<[]>;


          And let's try it:



          var result = loader.add(1).add("hello").add(true).run(); //[number, string, boolean]


          Looks good. Hope that helps; good luck!




          UPDATE



          The above only works with --strictFunctionTypes enabled. If you must do without that compiler flag, you could use the following definition of Push instead:



          type PushTuple = [[0], [0, 0], [0, 0, 0],
          [0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0],
          [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0],
          [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
          ];
          type Push<
          T extends any[],
          V,
          L = PushTuple[T['length']],
          P = [K in keyof L]: K extends keyof T ? T[K] : V
          > = P extends any[] ? P : never;


          It's more terse for small supported tuple sizes, which is nice, but the repetition is quadratic in the number of supported tuples (O(n2) growth) instead of linear (O(n) growth), which is less nice. Anyway it works by using mapped tuples which were introduced in TS3.1.



          It's up to you.



          Good luck again!






          share|improve this answer

























          • This is an awesome solution. I'm totally fine with picking a reasonable maximum. However, I tried using your example exactly as you provided, and the type inferred from result is [number, ...undefined[]]. Is it possible that your example isn't quite correct? I'm using typescript 3.1.6

            – TwitchBronBron
            Mar 8 at 19:07











          • Turn on --strict for your own sake (or at least --strictFunctionTypes which seems to be the cause here) if you can. I'm sure there's some change I could make to have Push work without it, but --strict is so useful that I try to spend as little time as possible with it off.

            – jcalz
            Mar 9 at 16:31











          • updated with version of Push that works without --strict

            – jcalz
            Mar 9 at 16:56











          • --strict did the trick. Thanks!

            – TwitchBronBron
            Mar 15 at 11:52











          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%2f55066970%2fgeneric-object-return-type-is-result-of-method-chaining%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














          There is unfortunately no supported way in TypeScript to represent the type operation of appending a type onto the end of a tuple. I'll call this operation Push<T, V> where T is a tuple and V is any value type. There is a way to represent prepending a value onto the beginning of a tuple, which I'll call Cons<V, T>. That's because in TypeScript 3.0, a feature was introduced to treat tuples as the types of function parameters. We can also get Tail<T>, which pulls the first element (the head) off a tuple and returns the rest:



          type Cons<H, T extends any[]> = 
          ((h: H, ...t: T) => void) extends ((...r: infer R) => void) ? R : never;
          type Tail<T extends any[]> =
          ((...x: T) => void) extends ((h: infer A, ...t: infer R) => void) ? R : never;


          Given Cons and Tail, the natural representation of Push would be this recursive thing that doesn't work:



          type BadPush<T extends any[], V> = 
          T['length'] extends 0 ? [V] : Cons<T[0], BadPush<Tail<T>, V>>; // error, circular


          The idea there is that Push<[], V> should just be [V] (appending to an empty tuple is easy), and Push<[H, ...T], V> is Cons<H, Push<T, V>> (you hold onto the first element H and just push V onto the tail T... then prepend H back onto the result).



          While possible to trick the compiler into allowing such recursive types, it is not recommended. What I usually do instead is pick some maximum reasonable length of tuple I want to support modifying (say 9 or 10) and then unroll the circular definition:



          type Push<T extends any[], V> = T['length'] extends 0 ? [V] : Cons<T[0], Push1<Tail<T>, V>>
          type Push1<T extends any[], V> = T['length'] extends 0 ? [V] : Cons<T[0], Push2<Tail<T>, V>>
          type Push2<T extends any[], V> = T['length'] extends 0 ? [V] : Cons<T[0], Push3<Tail<T>, V>>
          type Push3<T extends any[], V> = T['length'] extends 0 ? [V] : Cons<T[0], Push4<Tail<T>, V>>
          type Push4<T extends any[], V> = T['length'] extends 0 ? [V] : Cons<T[0], Push5<Tail<T>, V>>
          type Push5<T extends any[], V> = T['length'] extends 0 ? [V] : Cons<T[0], Push6<Tail<T>, V>>
          type Push6<T extends any[], V> = T['length'] extends 0 ? [V] : Cons<T[0], Push7<Tail<T>, V>>
          type Push7<T extends any[], V> = T['length'] extends 0 ? [V] : Cons<T[0], Push8<Tail<T>, V>>
          type Push8<T extends any[], V> = T['length'] extends 0 ? [V] : Cons<T[0], Push9<Tail<T>, V>>
          type Push9<T extends any[], V> = T['length'] extends 0 ? [V] : Cons<T[0], PushX<Tail<T>, V>>
          type PushX<T extends any[], V> = Array<T[number] | V>; // give up


          Each line except PushX looks just like the recursive definition, and we intentionally cut things off at PushX by giving up and just forgetting about the order of elements (PushX<[1,2,3],4> is Array<1 | 2 | 3 | 4>).



          Now we can do this:



          type Test = Push<[1, 2, 3, 4, 5, 6, 7, 8], 9> // [1, 2, 3, 4, 5, 6, 7, 8, 9]



          Armed with Push, let's give a type to loader (leaving the implementation up to you):



          type Loader<T extends any[]> = 
          add<V>(x: V): Loader<Push<T, V>>;
          run(): T

          declare const loader: Loader<[]>;


          And let's try it:



          var result = loader.add(1).add("hello").add(true).run(); //[number, string, boolean]


          Looks good. Hope that helps; good luck!




          UPDATE



          The above only works with --strictFunctionTypes enabled. If you must do without that compiler flag, you could use the following definition of Push instead:



          type PushTuple = [[0], [0, 0], [0, 0, 0],
          [0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0],
          [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0],
          [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
          ];
          type Push<
          T extends any[],
          V,
          L = PushTuple[T['length']],
          P = [K in keyof L]: K extends keyof T ? T[K] : V
          > = P extends any[] ? P : never;


          It's more terse for small supported tuple sizes, which is nice, but the repetition is quadratic in the number of supported tuples (O(n2) growth) instead of linear (O(n) growth), which is less nice. Anyway it works by using mapped tuples which were introduced in TS3.1.



          It's up to you.



          Good luck again!






          share|improve this answer

























          • This is an awesome solution. I'm totally fine with picking a reasonable maximum. However, I tried using your example exactly as you provided, and the type inferred from result is [number, ...undefined[]]. Is it possible that your example isn't quite correct? I'm using typescript 3.1.6

            – TwitchBronBron
            Mar 8 at 19:07











          • Turn on --strict for your own sake (or at least --strictFunctionTypes which seems to be the cause here) if you can. I'm sure there's some change I could make to have Push work without it, but --strict is so useful that I try to spend as little time as possible with it off.

            – jcalz
            Mar 9 at 16:31











          • updated with version of Push that works without --strict

            – jcalz
            Mar 9 at 16:56











          • --strict did the trick. Thanks!

            – TwitchBronBron
            Mar 15 at 11:52















          1














          There is unfortunately no supported way in TypeScript to represent the type operation of appending a type onto the end of a tuple. I'll call this operation Push<T, V> where T is a tuple and V is any value type. There is a way to represent prepending a value onto the beginning of a tuple, which I'll call Cons<V, T>. That's because in TypeScript 3.0, a feature was introduced to treat tuples as the types of function parameters. We can also get Tail<T>, which pulls the first element (the head) off a tuple and returns the rest:



          type Cons<H, T extends any[]> = 
          ((h: H, ...t: T) => void) extends ((...r: infer R) => void) ? R : never;
          type Tail<T extends any[]> =
          ((...x: T) => void) extends ((h: infer A, ...t: infer R) => void) ? R : never;


          Given Cons and Tail, the natural representation of Push would be this recursive thing that doesn't work:



          type BadPush<T extends any[], V> = 
          T['length'] extends 0 ? [V] : Cons<T[0], BadPush<Tail<T>, V>>; // error, circular


          The idea there is that Push<[], V> should just be [V] (appending to an empty tuple is easy), and Push<[H, ...T], V> is Cons<H, Push<T, V>> (you hold onto the first element H and just push V onto the tail T... then prepend H back onto the result).



          While possible to trick the compiler into allowing such recursive types, it is not recommended. What I usually do instead is pick some maximum reasonable length of tuple I want to support modifying (say 9 or 10) and then unroll the circular definition:



          type Push<T extends any[], V> = T['length'] extends 0 ? [V] : Cons<T[0], Push1<Tail<T>, V>>
          type Push1<T extends any[], V> = T['length'] extends 0 ? [V] : Cons<T[0], Push2<Tail<T>, V>>
          type Push2<T extends any[], V> = T['length'] extends 0 ? [V] : Cons<T[0], Push3<Tail<T>, V>>
          type Push3<T extends any[], V> = T['length'] extends 0 ? [V] : Cons<T[0], Push4<Tail<T>, V>>
          type Push4<T extends any[], V> = T['length'] extends 0 ? [V] : Cons<T[0], Push5<Tail<T>, V>>
          type Push5<T extends any[], V> = T['length'] extends 0 ? [V] : Cons<T[0], Push6<Tail<T>, V>>
          type Push6<T extends any[], V> = T['length'] extends 0 ? [V] : Cons<T[0], Push7<Tail<T>, V>>
          type Push7<T extends any[], V> = T['length'] extends 0 ? [V] : Cons<T[0], Push8<Tail<T>, V>>
          type Push8<T extends any[], V> = T['length'] extends 0 ? [V] : Cons<T[0], Push9<Tail<T>, V>>
          type Push9<T extends any[], V> = T['length'] extends 0 ? [V] : Cons<T[0], PushX<Tail<T>, V>>
          type PushX<T extends any[], V> = Array<T[number] | V>; // give up


          Each line except PushX looks just like the recursive definition, and we intentionally cut things off at PushX by giving up and just forgetting about the order of elements (PushX<[1,2,3],4> is Array<1 | 2 | 3 | 4>).



          Now we can do this:



          type Test = Push<[1, 2, 3, 4, 5, 6, 7, 8], 9> // [1, 2, 3, 4, 5, 6, 7, 8, 9]



          Armed with Push, let's give a type to loader (leaving the implementation up to you):



          type Loader<T extends any[]> = 
          add<V>(x: V): Loader<Push<T, V>>;
          run(): T

          declare const loader: Loader<[]>;


          And let's try it:



          var result = loader.add(1).add("hello").add(true).run(); //[number, string, boolean]


          Looks good. Hope that helps; good luck!




          UPDATE



          The above only works with --strictFunctionTypes enabled. If you must do without that compiler flag, you could use the following definition of Push instead:



          type PushTuple = [[0], [0, 0], [0, 0, 0],
          [0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0],
          [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0],
          [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
          ];
          type Push<
          T extends any[],
          V,
          L = PushTuple[T['length']],
          P = [K in keyof L]: K extends keyof T ? T[K] : V
          > = P extends any[] ? P : never;


          It's more terse for small supported tuple sizes, which is nice, but the repetition is quadratic in the number of supported tuples (O(n2) growth) instead of linear (O(n) growth), which is less nice. Anyway it works by using mapped tuples which were introduced in TS3.1.



          It's up to you.



          Good luck again!






          share|improve this answer

























          • This is an awesome solution. I'm totally fine with picking a reasonable maximum. However, I tried using your example exactly as you provided, and the type inferred from result is [number, ...undefined[]]. Is it possible that your example isn't quite correct? I'm using typescript 3.1.6

            – TwitchBronBron
            Mar 8 at 19:07











          • Turn on --strict for your own sake (or at least --strictFunctionTypes which seems to be the cause here) if you can. I'm sure there's some change I could make to have Push work without it, but --strict is so useful that I try to spend as little time as possible with it off.

            – jcalz
            Mar 9 at 16:31











          • updated with version of Push that works without --strict

            – jcalz
            Mar 9 at 16:56











          • --strict did the trick. Thanks!

            – TwitchBronBron
            Mar 15 at 11:52













          1












          1








          1







          There is unfortunately no supported way in TypeScript to represent the type operation of appending a type onto the end of a tuple. I'll call this operation Push<T, V> where T is a tuple and V is any value type. There is a way to represent prepending a value onto the beginning of a tuple, which I'll call Cons<V, T>. That's because in TypeScript 3.0, a feature was introduced to treat tuples as the types of function parameters. We can also get Tail<T>, which pulls the first element (the head) off a tuple and returns the rest:



          type Cons<H, T extends any[]> = 
          ((h: H, ...t: T) => void) extends ((...r: infer R) => void) ? R : never;
          type Tail<T extends any[]> =
          ((...x: T) => void) extends ((h: infer A, ...t: infer R) => void) ? R : never;


          Given Cons and Tail, the natural representation of Push would be this recursive thing that doesn't work:



          type BadPush<T extends any[], V> = 
          T['length'] extends 0 ? [V] : Cons<T[0], BadPush<Tail<T>, V>>; // error, circular


          The idea there is that Push<[], V> should just be [V] (appending to an empty tuple is easy), and Push<[H, ...T], V> is Cons<H, Push<T, V>> (you hold onto the first element H and just push V onto the tail T... then prepend H back onto the result).



          While possible to trick the compiler into allowing such recursive types, it is not recommended. What I usually do instead is pick some maximum reasonable length of tuple I want to support modifying (say 9 or 10) and then unroll the circular definition:



          type Push<T extends any[], V> = T['length'] extends 0 ? [V] : Cons<T[0], Push1<Tail<T>, V>>
          type Push1<T extends any[], V> = T['length'] extends 0 ? [V] : Cons<T[0], Push2<Tail<T>, V>>
          type Push2<T extends any[], V> = T['length'] extends 0 ? [V] : Cons<T[0], Push3<Tail<T>, V>>
          type Push3<T extends any[], V> = T['length'] extends 0 ? [V] : Cons<T[0], Push4<Tail<T>, V>>
          type Push4<T extends any[], V> = T['length'] extends 0 ? [V] : Cons<T[0], Push5<Tail<T>, V>>
          type Push5<T extends any[], V> = T['length'] extends 0 ? [V] : Cons<T[0], Push6<Tail<T>, V>>
          type Push6<T extends any[], V> = T['length'] extends 0 ? [V] : Cons<T[0], Push7<Tail<T>, V>>
          type Push7<T extends any[], V> = T['length'] extends 0 ? [V] : Cons<T[0], Push8<Tail<T>, V>>
          type Push8<T extends any[], V> = T['length'] extends 0 ? [V] : Cons<T[0], Push9<Tail<T>, V>>
          type Push9<T extends any[], V> = T['length'] extends 0 ? [V] : Cons<T[0], PushX<Tail<T>, V>>
          type PushX<T extends any[], V> = Array<T[number] | V>; // give up


          Each line except PushX looks just like the recursive definition, and we intentionally cut things off at PushX by giving up and just forgetting about the order of elements (PushX<[1,2,3],4> is Array<1 | 2 | 3 | 4>).



          Now we can do this:



          type Test = Push<[1, 2, 3, 4, 5, 6, 7, 8], 9> // [1, 2, 3, 4, 5, 6, 7, 8, 9]



          Armed with Push, let's give a type to loader (leaving the implementation up to you):



          type Loader<T extends any[]> = 
          add<V>(x: V): Loader<Push<T, V>>;
          run(): T

          declare const loader: Loader<[]>;


          And let's try it:



          var result = loader.add(1).add("hello").add(true).run(); //[number, string, boolean]


          Looks good. Hope that helps; good luck!




          UPDATE



          The above only works with --strictFunctionTypes enabled. If you must do without that compiler flag, you could use the following definition of Push instead:



          type PushTuple = [[0], [0, 0], [0, 0, 0],
          [0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0],
          [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0],
          [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
          ];
          type Push<
          T extends any[],
          V,
          L = PushTuple[T['length']],
          P = [K in keyof L]: K extends keyof T ? T[K] : V
          > = P extends any[] ? P : never;


          It's more terse for small supported tuple sizes, which is nice, but the repetition is quadratic in the number of supported tuples (O(n2) growth) instead of linear (O(n) growth), which is less nice. Anyway it works by using mapped tuples which were introduced in TS3.1.



          It's up to you.



          Good luck again!






          share|improve this answer















          There is unfortunately no supported way in TypeScript to represent the type operation of appending a type onto the end of a tuple. I'll call this operation Push<T, V> where T is a tuple and V is any value type. There is a way to represent prepending a value onto the beginning of a tuple, which I'll call Cons<V, T>. That's because in TypeScript 3.0, a feature was introduced to treat tuples as the types of function parameters. We can also get Tail<T>, which pulls the first element (the head) off a tuple and returns the rest:



          type Cons<H, T extends any[]> = 
          ((h: H, ...t: T) => void) extends ((...r: infer R) => void) ? R : never;
          type Tail<T extends any[]> =
          ((...x: T) => void) extends ((h: infer A, ...t: infer R) => void) ? R : never;


          Given Cons and Tail, the natural representation of Push would be this recursive thing that doesn't work:



          type BadPush<T extends any[], V> = 
          T['length'] extends 0 ? [V] : Cons<T[0], BadPush<Tail<T>, V>>; // error, circular


          The idea there is that Push<[], V> should just be [V] (appending to an empty tuple is easy), and Push<[H, ...T], V> is Cons<H, Push<T, V>> (you hold onto the first element H and just push V onto the tail T... then prepend H back onto the result).



          While possible to trick the compiler into allowing such recursive types, it is not recommended. What I usually do instead is pick some maximum reasonable length of tuple I want to support modifying (say 9 or 10) and then unroll the circular definition:



          type Push<T extends any[], V> = T['length'] extends 0 ? [V] : Cons<T[0], Push1<Tail<T>, V>>
          type Push1<T extends any[], V> = T['length'] extends 0 ? [V] : Cons<T[0], Push2<Tail<T>, V>>
          type Push2<T extends any[], V> = T['length'] extends 0 ? [V] : Cons<T[0], Push3<Tail<T>, V>>
          type Push3<T extends any[], V> = T['length'] extends 0 ? [V] : Cons<T[0], Push4<Tail<T>, V>>
          type Push4<T extends any[], V> = T['length'] extends 0 ? [V] : Cons<T[0], Push5<Tail<T>, V>>
          type Push5<T extends any[], V> = T['length'] extends 0 ? [V] : Cons<T[0], Push6<Tail<T>, V>>
          type Push6<T extends any[], V> = T['length'] extends 0 ? [V] : Cons<T[0], Push7<Tail<T>, V>>
          type Push7<T extends any[], V> = T['length'] extends 0 ? [V] : Cons<T[0], Push8<Tail<T>, V>>
          type Push8<T extends any[], V> = T['length'] extends 0 ? [V] : Cons<T[0], Push9<Tail<T>, V>>
          type Push9<T extends any[], V> = T['length'] extends 0 ? [V] : Cons<T[0], PushX<Tail<T>, V>>
          type PushX<T extends any[], V> = Array<T[number] | V>; // give up


          Each line except PushX looks just like the recursive definition, and we intentionally cut things off at PushX by giving up and just forgetting about the order of elements (PushX<[1,2,3],4> is Array<1 | 2 | 3 | 4>).



          Now we can do this:



          type Test = Push<[1, 2, 3, 4, 5, 6, 7, 8], 9> // [1, 2, 3, 4, 5, 6, 7, 8, 9]



          Armed with Push, let's give a type to loader (leaving the implementation up to you):



          type Loader<T extends any[]> = 
          add<V>(x: V): Loader<Push<T, V>>;
          run(): T

          declare const loader: Loader<[]>;


          And let's try it:



          var result = loader.add(1).add("hello").add(true).run(); //[number, string, boolean]


          Looks good. Hope that helps; good luck!




          UPDATE



          The above only works with --strictFunctionTypes enabled. If you must do without that compiler flag, you could use the following definition of Push instead:



          type PushTuple = [[0], [0, 0], [0, 0, 0],
          [0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0],
          [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0],
          [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
          ];
          type Push<
          T extends any[],
          V,
          L = PushTuple[T['length']],
          P = [K in keyof L]: K extends keyof T ? T[K] : V
          > = P extends any[] ? P : never;


          It's more terse for small supported tuple sizes, which is nice, but the repetition is quadratic in the number of supported tuples (O(n2) growth) instead of linear (O(n) growth), which is less nice. Anyway it works by using mapped tuples which were introduced in TS3.1.



          It's up to you.



          Good luck again!







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 9 at 16:56

























          answered Mar 8 at 16:56









          jcalzjcalz

          30.2k22850




          30.2k22850












          • This is an awesome solution. I'm totally fine with picking a reasonable maximum. However, I tried using your example exactly as you provided, and the type inferred from result is [number, ...undefined[]]. Is it possible that your example isn't quite correct? I'm using typescript 3.1.6

            – TwitchBronBron
            Mar 8 at 19:07











          • Turn on --strict for your own sake (or at least --strictFunctionTypes which seems to be the cause here) if you can. I'm sure there's some change I could make to have Push work without it, but --strict is so useful that I try to spend as little time as possible with it off.

            – jcalz
            Mar 9 at 16:31











          • updated with version of Push that works without --strict

            – jcalz
            Mar 9 at 16:56











          • --strict did the trick. Thanks!

            – TwitchBronBron
            Mar 15 at 11:52

















          • This is an awesome solution. I'm totally fine with picking a reasonable maximum. However, I tried using your example exactly as you provided, and the type inferred from result is [number, ...undefined[]]. Is it possible that your example isn't quite correct? I'm using typescript 3.1.6

            – TwitchBronBron
            Mar 8 at 19:07











          • Turn on --strict for your own sake (or at least --strictFunctionTypes which seems to be the cause here) if you can. I'm sure there's some change I could make to have Push work without it, but --strict is so useful that I try to spend as little time as possible with it off.

            – jcalz
            Mar 9 at 16:31











          • updated with version of Push that works without --strict

            – jcalz
            Mar 9 at 16:56











          • --strict did the trick. Thanks!

            – TwitchBronBron
            Mar 15 at 11:52
















          This is an awesome solution. I'm totally fine with picking a reasonable maximum. However, I tried using your example exactly as you provided, and the type inferred from result is [number, ...undefined[]]. Is it possible that your example isn't quite correct? I'm using typescript 3.1.6

          – TwitchBronBron
          Mar 8 at 19:07





          This is an awesome solution. I'm totally fine with picking a reasonable maximum. However, I tried using your example exactly as you provided, and the type inferred from result is [number, ...undefined[]]. Is it possible that your example isn't quite correct? I'm using typescript 3.1.6

          – TwitchBronBron
          Mar 8 at 19:07













          Turn on --strict for your own sake (or at least --strictFunctionTypes which seems to be the cause here) if you can. I'm sure there's some change I could make to have Push work without it, but --strict is so useful that I try to spend as little time as possible with it off.

          – jcalz
          Mar 9 at 16:31





          Turn on --strict for your own sake (or at least --strictFunctionTypes which seems to be the cause here) if you can. I'm sure there's some change I could make to have Push work without it, but --strict is so useful that I try to spend as little time as possible with it off.

          – jcalz
          Mar 9 at 16:31













          updated with version of Push that works without --strict

          – jcalz
          Mar 9 at 16:56





          updated with version of Push that works without --strict

          – jcalz
          Mar 9 at 16:56













          --strict did the trick. Thanks!

          – TwitchBronBron
          Mar 15 at 11:52





          --strict did the trick. Thanks!

          – TwitchBronBron
          Mar 15 at 11:52



















          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%2f55066970%2fgeneric-object-return-type-is-result-of-method-chaining%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

          Thal And Out Agency railway station See also References External links Navigation menuOfficial Web Site of Pakistan RailwaysArchivedOfficial Web Site of Pakistan Railwayseeexpanding ite

          Understanding generators in Python2019 Community Moderator ElectionGenerator function not working pythonFor loop not executing two timesGenerators - Printing generated valuesWhy can a python generator only be used once?What exactly do generators do?What does the “yield” keyword do?What does “list comprehension” mean? How does it work and how can I use it?sklearn Kfold acces single fold instead of for loopIs a generator the callable? Which is the generator?Apply Border To Range Of Cells Using OpenpyxlCalling an external command in PythonWhat are metaclasses in Python?What is the difference between @staticmethod and @classmethod?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?Understanding slice notationUnderstanding Python super() with __init__() methodsDoes Python have a string 'contains' substring method?

          How can I change the color of pagination dots of UIPageControl?How to change UIPageControl dotsIs there a way to change page indicator dots colorCustomize dot with image of UIPageControl at index 0 of UIPageControlNo visible @interface for 'NSObject<PageControlDelegate>' declares the selector 'pageControlPageDidChange:'How to change the color of pagination dots in UIPageControl with a different color per pagepagecontrol indicator custom image instead of DefaultChanging the colour of UIPageControl dots in MonoTouchpagecontrol selectable page visibility color?Alternative way to load ViewControllers on a UIPageControlHow to set only layer.border-color for UIpage control dots in swiftHow can I develop for iPhone using a Windows development machine?How to change the name of an iOS app?UITableView - change section header coloruipagecontrol indicator(dot)issueCustom UIPageControl dots color not changingchange the interspace between UIPageControl dotsHow to change Status Bar text color in iOSHow can I change image tintColor in iOS and WatchKitUIPageControl dots with larger space in between each dotsHow to change the color of pagination dots in UIPageControl with a different color per page