typescript

Uncaught TypeError: Typescript extension method not a function


I'm trying to write an extension method for Array. Whenever the program runs the code, I get Uncaught TypeError: pairs.map(...).flatten is not a function. Here's what the code looks like:

extensions.ts

declare interface Array<T> {
  flatten<T>(): T;
}

Array.prototype.flatten = function<T> () : T {
  return this.reduce(function (flat: Array<T>, toFlatten: Array<T>) {
    return flat.concat(Array.isArray(toFlatten) ? toFlatten.flatten() : toFlatten )
  }, []);
}

values.ts

export let pairs: { start: String[], end: String[] }[] = [
  { start: [ ... ], end: [ ... ] }, ...
];
export let items: String[] = pairs.map(pair => pair.start.concat(pair.end)).flatten();

I've tried changing Array.prototype.flatten = function<T> () : T { ... to Array.prototype.flatten = <T> () : T => { ... and pairs.map(pair => pair.start.concat(pair.end)).flatten() to pairs.map(pair => pair.start.concat(pair.end)).flatten<String[]>() but it didn't do anything.

I've also read somewhere here that it could have been a transpiling problem so I changed the --target compiler to ESNext, but the error has still been popping up.


Solution

  • What you're seeing is a runtime exception. While your type definitions provide TS with everything it needs to compile your code, you'll need to make sure to include the definition of flatten near the top of your entry file (before you invoke it), otherwise JS engine won't know it exists on the Array prototype.