Type definition for a jagged array of type T and its array prototype extension












2














I'm trying to write a Typescript definition file for a JavaScript function I've attached to Array.prototype.



Array.js



/**
* Flattens the array recursively.
*
* @example
* [1, [2, 3]].flat() // => [1, 2, 3]
*
* @example
* [[1, [2, 3], [4, [5]]], 6].flat() // => [1, 2, 3, 4, 5, 6]
*/
Array.prototype.flat = function () {
return this.reduce((arr, val) => Array.isArray(val) ? arr.concat(val.flat()) : arr.concat(val), );
}


flat() works on an Array<T|S> where S is Array<T|S> and returns Array<T>. That is, it has a recursive definition, and all arrays fit the definition, as [1, 2, 3].flat() will simply return a copy of the original array.



I'm new to TypeScript, but my understanding is that in order to get the benefits of a TypeScript definition file (namely IntelliSense), the method definition must be within interface Array<T>. If this is the case, is there a way to place a constraint on T for a specialized version of Array<T>?



If not, how can I define an interface that will be picked up for every array AND will recognize when the array fits the recursive definition?










share|improve this question





























    2














    I'm trying to write a Typescript definition file for a JavaScript function I've attached to Array.prototype.



    Array.js



    /**
    * Flattens the array recursively.
    *
    * @example
    * [1, [2, 3]].flat() // => [1, 2, 3]
    *
    * @example
    * [[1, [2, 3], [4, [5]]], 6].flat() // => [1, 2, 3, 4, 5, 6]
    */
    Array.prototype.flat = function () {
    return this.reduce((arr, val) => Array.isArray(val) ? arr.concat(val.flat()) : arr.concat(val), );
    }


    flat() works on an Array<T|S> where S is Array<T|S> and returns Array<T>. That is, it has a recursive definition, and all arrays fit the definition, as [1, 2, 3].flat() will simply return a copy of the original array.



    I'm new to TypeScript, but my understanding is that in order to get the benefits of a TypeScript definition file (namely IntelliSense), the method definition must be within interface Array<T>. If this is the case, is there a way to place a constraint on T for a specialized version of Array<T>?



    If not, how can I define an interface that will be picked up for every array AND will recognize when the array fits the recursive definition?










    share|improve this question



























      2












      2








      2







      I'm trying to write a Typescript definition file for a JavaScript function I've attached to Array.prototype.



      Array.js



      /**
      * Flattens the array recursively.
      *
      * @example
      * [1, [2, 3]].flat() // => [1, 2, 3]
      *
      * @example
      * [[1, [2, 3], [4, [5]]], 6].flat() // => [1, 2, 3, 4, 5, 6]
      */
      Array.prototype.flat = function () {
      return this.reduce((arr, val) => Array.isArray(val) ? arr.concat(val.flat()) : arr.concat(val), );
      }


      flat() works on an Array<T|S> where S is Array<T|S> and returns Array<T>. That is, it has a recursive definition, and all arrays fit the definition, as [1, 2, 3].flat() will simply return a copy of the original array.



      I'm new to TypeScript, but my understanding is that in order to get the benefits of a TypeScript definition file (namely IntelliSense), the method definition must be within interface Array<T>. If this is the case, is there a way to place a constraint on T for a specialized version of Array<T>?



      If not, how can I define an interface that will be picked up for every array AND will recognize when the array fits the recursive definition?










      share|improve this question















      I'm trying to write a Typescript definition file for a JavaScript function I've attached to Array.prototype.



      Array.js



      /**
      * Flattens the array recursively.
      *
      * @example
      * [1, [2, 3]].flat() // => [1, 2, 3]
      *
      * @example
      * [[1, [2, 3], [4, [5]]], 6].flat() // => [1, 2, 3, 4, 5, 6]
      */
      Array.prototype.flat = function () {
      return this.reduce((arr, val) => Array.isArray(val) ? arr.concat(val.flat()) : arr.concat(val), );
      }


      flat() works on an Array<T|S> where S is Array<T|S> and returns Array<T>. That is, it has a recursive definition, and all arrays fit the definition, as [1, 2, 3].flat() will simply return a copy of the original array.



      I'm new to TypeScript, but my understanding is that in order to get the benefits of a TypeScript definition file (namely IntelliSense), the method definition must be within interface Array<T>. If this is the case, is there a way to place a constraint on T for a specialized version of Array<T>?



      If not, how can I define an interface that will be picked up for every array AND will recognize when the array fits the recursive definition?







      javascript typescript typescript-generics






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 20 at 6:23









      Shaun Luttin

      57.3k32220281




      57.3k32220281










      asked Nov 20 at 2:55









      dfoverdx

      1,54842345




      1,54842345
























          1 Answer
          1






          active

          oldest

          votes


















          3














          This is not a complete answer, but it does get us most of the way. Here it is in the TypeScript Playground.



          type JaggedArrayItem<T> = T | JaggedArray<T>;

          interface JaggedArray<T> extends Array<JaggedArrayItem<T>> { }

          type FlatArray<T> = T extends JaggedArrayItem<infer U> ? U : T;

          interface Array<T> {
          flat(this: JaggedArray<T>): FlatArray<T>;
          }

          Array.prototype.flat = function () {
          return this.reduce(
          (arr, val) => Array.isArray(val)
          ? arr.concat(val.flat())
          : arr.concat(val),
          );
          };

          // Test

          const myRecursiveArray: JaggedArray<number> = [
          10,
          [9],
          [
          [8],
          [
          [7],
          ]
          ],
          ];

          const flattened: number = myRecursiveArray.flat();
          const flattenedToo: (string | number) = [1, 'two'].flat();


          See also




          • https://github.com/Microsoft/TypeScript/issues/3496#issuecomment-128553540

          • https://github.com/shaunluttin/typescript-jagged-array-type-and-prototype






          share|improve this answer























          • Is there a reason we need FlatArray<T>? Can't flat()'s signature simply be flat(this: JaggedArray<T>): Array<T>;? I'm also unsure of why we need to surface an error for union types. [ 1, 'foo' ].flat() should work, no?
            – dfoverdx
            Nov 21 at 17:55












          • @dfoverdx Good point about the TODO item for surfacing an error. I put that in there because I though that the original question wanted to avoid union types... I think I was mistaken about that, so I deleted that TODO item.
            – Shaun Luttin
            Nov 21 at 19:50










          • @dfoverdx If we return Array<T> instead of FlatArray<T>, then resultant type will not be a T. For instance, the number example would return this error at compile time: Type 'JaggedArrayItem<number>' is not assignable to type 'number'. Type 'JaggedArrayItem<number>' is not assignable to type 'number'. Type 'JaggedArray<number>' is not assignable to type 'number'.
            – Shaun Luttin
            Nov 21 at 19:55













          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%2f53385558%2ftype-definition-for-a-jagged-array-of-type-t-and-its-array-prototype-extension%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









          3














          This is not a complete answer, but it does get us most of the way. Here it is in the TypeScript Playground.



          type JaggedArrayItem<T> = T | JaggedArray<T>;

          interface JaggedArray<T> extends Array<JaggedArrayItem<T>> { }

          type FlatArray<T> = T extends JaggedArrayItem<infer U> ? U : T;

          interface Array<T> {
          flat(this: JaggedArray<T>): FlatArray<T>;
          }

          Array.prototype.flat = function () {
          return this.reduce(
          (arr, val) => Array.isArray(val)
          ? arr.concat(val.flat())
          : arr.concat(val),
          );
          };

          // Test

          const myRecursiveArray: JaggedArray<number> = [
          10,
          [9],
          [
          [8],
          [
          [7],
          ]
          ],
          ];

          const flattened: number = myRecursiveArray.flat();
          const flattenedToo: (string | number) = [1, 'two'].flat();


          See also




          • https://github.com/Microsoft/TypeScript/issues/3496#issuecomment-128553540

          • https://github.com/shaunluttin/typescript-jagged-array-type-and-prototype






          share|improve this answer























          • Is there a reason we need FlatArray<T>? Can't flat()'s signature simply be flat(this: JaggedArray<T>): Array<T>;? I'm also unsure of why we need to surface an error for union types. [ 1, 'foo' ].flat() should work, no?
            – dfoverdx
            Nov 21 at 17:55












          • @dfoverdx Good point about the TODO item for surfacing an error. I put that in there because I though that the original question wanted to avoid union types... I think I was mistaken about that, so I deleted that TODO item.
            – Shaun Luttin
            Nov 21 at 19:50










          • @dfoverdx If we return Array<T> instead of FlatArray<T>, then resultant type will not be a T. For instance, the number example would return this error at compile time: Type 'JaggedArrayItem<number>' is not assignable to type 'number'. Type 'JaggedArrayItem<number>' is not assignable to type 'number'. Type 'JaggedArray<number>' is not assignable to type 'number'.
            – Shaun Luttin
            Nov 21 at 19:55


















          3














          This is not a complete answer, but it does get us most of the way. Here it is in the TypeScript Playground.



          type JaggedArrayItem<T> = T | JaggedArray<T>;

          interface JaggedArray<T> extends Array<JaggedArrayItem<T>> { }

          type FlatArray<T> = T extends JaggedArrayItem<infer U> ? U : T;

          interface Array<T> {
          flat(this: JaggedArray<T>): FlatArray<T>;
          }

          Array.prototype.flat = function () {
          return this.reduce(
          (arr, val) => Array.isArray(val)
          ? arr.concat(val.flat())
          : arr.concat(val),
          );
          };

          // Test

          const myRecursiveArray: JaggedArray<number> = [
          10,
          [9],
          [
          [8],
          [
          [7],
          ]
          ],
          ];

          const flattened: number = myRecursiveArray.flat();
          const flattenedToo: (string | number) = [1, 'two'].flat();


          See also




          • https://github.com/Microsoft/TypeScript/issues/3496#issuecomment-128553540

          • https://github.com/shaunluttin/typescript-jagged-array-type-and-prototype






          share|improve this answer























          • Is there a reason we need FlatArray<T>? Can't flat()'s signature simply be flat(this: JaggedArray<T>): Array<T>;? I'm also unsure of why we need to surface an error for union types. [ 1, 'foo' ].flat() should work, no?
            – dfoverdx
            Nov 21 at 17:55












          • @dfoverdx Good point about the TODO item for surfacing an error. I put that in there because I though that the original question wanted to avoid union types... I think I was mistaken about that, so I deleted that TODO item.
            – Shaun Luttin
            Nov 21 at 19:50










          • @dfoverdx If we return Array<T> instead of FlatArray<T>, then resultant type will not be a T. For instance, the number example would return this error at compile time: Type 'JaggedArrayItem<number>' is not assignable to type 'number'. Type 'JaggedArrayItem<number>' is not assignable to type 'number'. Type 'JaggedArray<number>' is not assignable to type 'number'.
            – Shaun Luttin
            Nov 21 at 19:55
















          3












          3








          3






          This is not a complete answer, but it does get us most of the way. Here it is in the TypeScript Playground.



          type JaggedArrayItem<T> = T | JaggedArray<T>;

          interface JaggedArray<T> extends Array<JaggedArrayItem<T>> { }

          type FlatArray<T> = T extends JaggedArrayItem<infer U> ? U : T;

          interface Array<T> {
          flat(this: JaggedArray<T>): FlatArray<T>;
          }

          Array.prototype.flat = function () {
          return this.reduce(
          (arr, val) => Array.isArray(val)
          ? arr.concat(val.flat())
          : arr.concat(val),
          );
          };

          // Test

          const myRecursiveArray: JaggedArray<number> = [
          10,
          [9],
          [
          [8],
          [
          [7],
          ]
          ],
          ];

          const flattened: number = myRecursiveArray.flat();
          const flattenedToo: (string | number) = [1, 'two'].flat();


          See also




          • https://github.com/Microsoft/TypeScript/issues/3496#issuecomment-128553540

          • https://github.com/shaunluttin/typescript-jagged-array-type-and-prototype






          share|improve this answer














          This is not a complete answer, but it does get us most of the way. Here it is in the TypeScript Playground.



          type JaggedArrayItem<T> = T | JaggedArray<T>;

          interface JaggedArray<T> extends Array<JaggedArrayItem<T>> { }

          type FlatArray<T> = T extends JaggedArrayItem<infer U> ? U : T;

          interface Array<T> {
          flat(this: JaggedArray<T>): FlatArray<T>;
          }

          Array.prototype.flat = function () {
          return this.reduce(
          (arr, val) => Array.isArray(val)
          ? arr.concat(val.flat())
          : arr.concat(val),
          );
          };

          // Test

          const myRecursiveArray: JaggedArray<number> = [
          10,
          [9],
          [
          [8],
          [
          [7],
          ]
          ],
          ];

          const flattened: number = myRecursiveArray.flat();
          const flattenedToo: (string | number) = [1, 'two'].flat();


          See also




          • https://github.com/Microsoft/TypeScript/issues/3496#issuecomment-128553540

          • https://github.com/shaunluttin/typescript-jagged-array-type-and-prototype







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 21 at 19:51

























          answered Nov 20 at 4:27









          Shaun Luttin

          57.3k32220281




          57.3k32220281












          • Is there a reason we need FlatArray<T>? Can't flat()'s signature simply be flat(this: JaggedArray<T>): Array<T>;? I'm also unsure of why we need to surface an error for union types. [ 1, 'foo' ].flat() should work, no?
            – dfoverdx
            Nov 21 at 17:55












          • @dfoverdx Good point about the TODO item for surfacing an error. I put that in there because I though that the original question wanted to avoid union types... I think I was mistaken about that, so I deleted that TODO item.
            – Shaun Luttin
            Nov 21 at 19:50










          • @dfoverdx If we return Array<T> instead of FlatArray<T>, then resultant type will not be a T. For instance, the number example would return this error at compile time: Type 'JaggedArrayItem<number>' is not assignable to type 'number'. Type 'JaggedArrayItem<number>' is not assignable to type 'number'. Type 'JaggedArray<number>' is not assignable to type 'number'.
            – Shaun Luttin
            Nov 21 at 19:55




















          • Is there a reason we need FlatArray<T>? Can't flat()'s signature simply be flat(this: JaggedArray<T>): Array<T>;? I'm also unsure of why we need to surface an error for union types. [ 1, 'foo' ].flat() should work, no?
            – dfoverdx
            Nov 21 at 17:55












          • @dfoverdx Good point about the TODO item for surfacing an error. I put that in there because I though that the original question wanted to avoid union types... I think I was mistaken about that, so I deleted that TODO item.
            – Shaun Luttin
            Nov 21 at 19:50










          • @dfoverdx If we return Array<T> instead of FlatArray<T>, then resultant type will not be a T. For instance, the number example would return this error at compile time: Type 'JaggedArrayItem<number>' is not assignable to type 'number'. Type 'JaggedArrayItem<number>' is not assignable to type 'number'. Type 'JaggedArray<number>' is not assignable to type 'number'.
            – Shaun Luttin
            Nov 21 at 19:55


















          Is there a reason we need FlatArray<T>? Can't flat()'s signature simply be flat(this: JaggedArray<T>): Array<T>;? I'm also unsure of why we need to surface an error for union types. [ 1, 'foo' ].flat() should work, no?
          – dfoverdx
          Nov 21 at 17:55






          Is there a reason we need FlatArray<T>? Can't flat()'s signature simply be flat(this: JaggedArray<T>): Array<T>;? I'm also unsure of why we need to surface an error for union types. [ 1, 'foo' ].flat() should work, no?
          – dfoverdx
          Nov 21 at 17:55














          @dfoverdx Good point about the TODO item for surfacing an error. I put that in there because I though that the original question wanted to avoid union types... I think I was mistaken about that, so I deleted that TODO item.
          – Shaun Luttin
          Nov 21 at 19:50




          @dfoverdx Good point about the TODO item for surfacing an error. I put that in there because I though that the original question wanted to avoid union types... I think I was mistaken about that, so I deleted that TODO item.
          – Shaun Luttin
          Nov 21 at 19:50












          @dfoverdx If we return Array<T> instead of FlatArray<T>, then resultant type will not be a T. For instance, the number example would return this error at compile time: Type 'JaggedArrayItem<number>' is not assignable to type 'number'. Type 'JaggedArrayItem<number>' is not assignable to type 'number'. Type 'JaggedArray<number>' is not assignable to type 'number'.
          – Shaun Luttin
          Nov 21 at 19:55






          @dfoverdx If we return Array<T> instead of FlatArray<T>, then resultant type will not be a T. For instance, the number example would return this error at compile time: Type 'JaggedArrayItem<number>' is not assignable to type 'number'. Type 'JaggedArrayItem<number>' is not assignable to type 'number'. Type 'JaggedArray<number>' is not assignable to type 'number'.
          – Shaun Luttin
          Nov 21 at 19:55




















          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%2f53385558%2ftype-definition-for-a-jagged-array-of-type-t-and-its-array-prototype-extension%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

          If I really need a card on my start hand, how many mulligans make sense? [duplicate]

          Alcedinidae

          Can an atomic nucleus contain both particles and antiparticles? [duplicate]