Type definition for a jagged array of type T and its array prototype extension
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
add a comment |
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
add a comment |
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
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
javascript typescript typescript-generics
edited Nov 20 '18 at 6:23


Shaun Luttin
58.1k32223285
58.1k32223285
asked Nov 20 '18 at 2:55


dx_over_dtdx_over_dt
1,60342346
1,60342346
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
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
Is there a reason we needFlatArray<T>
? Can'tflat()
's signature simply beflat(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?
– dx_over_dt
Nov 21 '18 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 '18 at 19:50
@dfoverdx If we returnArray<T>
instead ofFlatArray<T>
, then resultant type will not be aT
. For instance, thenumber
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 '18 at 19:55
add a comment |
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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
Is there a reason we needFlatArray<T>
? Can'tflat()
's signature simply beflat(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?
– dx_over_dt
Nov 21 '18 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 '18 at 19:50
@dfoverdx If we returnArray<T>
instead ofFlatArray<T>
, then resultant type will not be aT
. For instance, thenumber
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 '18 at 19:55
add a comment |
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
Is there a reason we needFlatArray<T>
? Can'tflat()
's signature simply beflat(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?
– dx_over_dt
Nov 21 '18 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 '18 at 19:50
@dfoverdx If we returnArray<T>
instead ofFlatArray<T>
, then resultant type will not be aT
. For instance, thenumber
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 '18 at 19:55
add a comment |
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
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
edited Nov 21 '18 at 19:51
answered Nov 20 '18 at 4:27


Shaun LuttinShaun Luttin
58.1k32223285
58.1k32223285
Is there a reason we needFlatArray<T>
? Can'tflat()
's signature simply beflat(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?
– dx_over_dt
Nov 21 '18 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 '18 at 19:50
@dfoverdx If we returnArray<T>
instead ofFlatArray<T>
, then resultant type will not be aT
. For instance, thenumber
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 '18 at 19:55
add a comment |
Is there a reason we needFlatArray<T>
? Can'tflat()
's signature simply beflat(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?
– dx_over_dt
Nov 21 '18 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 '18 at 19:50
@dfoverdx If we returnArray<T>
instead ofFlatArray<T>
, then resultant type will not be aT
. For instance, thenumber
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 '18 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?– dx_over_dt
Nov 21 '18 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?– dx_over_dt
Nov 21 '18 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 '18 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 '18 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 '18 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 '18 at 19:55
add a comment |
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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