1

I can extend Array.prototype and use it in javascript like that:

Object.defineProperty(Array.prototype, 'flatten', {
  value: function flatten() {
      return this.reduce((a, b) => a.concat(b), []);
  }
});

// that allows me to do:
[1, 2, [3, 4]].flatten(); // [1,2,3,4]
[1, 2, [3, 4]].map(e => 5).flatten(); // [5, 5, 5]

However under typescript I get an Error: Property 'flatten' does not exist on type 'Array[]'.

I can avoid that doing something like the following, but that is not nice to get a fluent interface...it's harder to read.

 (<any>[1, 2, [3, 4]]).flatten()
 ([1, 2, [3, 4]].map(e => 5) as any).flatten()

Can I do something in typescript to avoid a casting to any? Like let to know typescript dynamically than the code of type Array has another method.

1 Answer 1

4

You can extend the Array<T> interface to add the flatten method:

declare global {
    interface Array<T> {
        flatten(): T[]
    }
}

Note that you only need to wrap it inside declare global only when you are inside a module. See merging interfaces.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.