For reference, I am using React 16.9.0
and Typescript 3.5.3
.
On this question How to extend an existing JavaScript array with another array, without creating a new array, I found how to create the new method extend
on the Array type:
Array.prototype.extend = function (other_array) {
/* You should include a test to check whether other_array really is an array */
other_array.forEach(function(v) {this.push(v)}, this);
}
But when I try to add Typescript support (for type checking the array type), I cannot find how to make it work. This is how I tried:
interface ExtendedArray< Type > extends Array< Type > {
extend: () => void;
}
if( !( 'extend' in Array.prototype ) ) {
Array.prototype.extend = function (other_array: ExtendedArray< any >) {
other_array.forEach( function(element) { this.push( element ) }, this );
}
}
Typescript just keep insisting my ExtendedArray type does not have the prototype.extend
attribute:
Property 'extend' does not exist on type 'any[]'. TS2339
52 | if( !( 'extend' in Array.prototype ) ) {
> 53 | Array.prototype.extend = function (other_array: ExtendedArray< any >) {
| ^
54 | other_array.forEach( function(element) { this.push( element ) }, this );
55 | }
56 | }
After searching more, I fond this other question Extending functionality in TypeScript, with this example:
interface String {
foo(): number;
}
String.prototype.foo= function() {
return 0;
}
But if I try to run it, Typescript just strikes its rage:
Property 'foo' does not exist on type 'String'. TS2339
41 | }
42 |
> 43 | String.prototype.foo= function() {
| ^
44 | return 0;
45 | }
46 |
How can I extend a Javascript builtin the prototype with a new function on Typescript?