1

In my TypeScript-based application I want to add some functionality to the Array-prototype.

Therefore I added a file Array.d.ts to my project which contains:

interface Array<T> {
    selectMany<TOut>(selectListFn: (t: T) => TOut[]): TOut[];
}

Then I created another file under /Scripts/Extentsions/Array.ts where I've implemented the function:

Array.prototype.selectMany = Array.prototype.selectMany || function<TIn, TOut>(selectListFn: (t: TIn) => TOut[]): TOut[] {
    return this.reduce((out, inx) => {
        out.push(...selectListFn(inx));
        return out;
    }, new Array<TOut>());
}

In another file I'm going to use the "extension" on an DivisionResource[]-array where DivisionResource is just the concrete type of the array's elements. Intellisense shows no errors but when running webpack it throws

TS2339: Property 'selectMany' does not exist on type 'DivisionResource[]'.

I don't get the point what is missing here.

1 Answer 1

1

You should wrap merging for global types with "global", like this;

declare global {
    interface Array<T> {
        selectMany<TOut>(selectListFn: (t: T) => TOut[]): TOut[];
    }
}

https://www.typescriptlang.org/docs/handbook/declaration-merging.html


You could also try adding a triple slash reference of declaration file to .ts file.

/// <reference path="../Array.d.ts" />
Sign up to request clarification or add additional context in comments.

2 Comments

This throws TS2669: Augmentations for the global scope can only be directly nested in external modules or ambient module declarations.
You are right, I got that error too (with TS 2.6.2). Could you try adding a reference of definition file to .ts file? /// <reference path="./Array.d.ts" />

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.