简体   繁体   中英

Extending Array's prototype not building in typescript

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.

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" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM