0

I have a library that has type definitions like this:

declare global {
    interface Array<T> {
        addRange<T>(elements: T[]): void;
        aggregate<U>(accumulator: (accum: U, value?: T, index?: number, list?: T[]) => any, initialValue?: U): any;
    }
}

This library is then exported to a NPM package, but how do I consume it in another project?

If I try doing:

['a', 'b'].addRange(['c', 'd']);

I get

Property 'addRange' does not exist on type

But I can't just import addRange because they are Array extensions.

How do I import this library so Typescript knows about it?

4
  • Can you share your tsconfig.json? are you using webpack or some other packaging technology? Commented Sep 3, 2019 at 16:25
  • @Amy you mean from the library or the project that consumes the library? Commented Sep 3, 2019 at 17:12
  • Your project which uses the library. My question pertains to your built tools. Commented Sep 3, 2019 at 17:13
  • That project is actually an Angular project, I haven't made any changes yet to it, except for just doing npm install. Commented Sep 3, 2019 at 17:14

2 Answers 2

1

You normally expose the types in package.json types field of the npm package. If these types include global type augmentations, they will be automatically picked up by the compiler, as soon as you require the package in the client project.

package.json (library):

{
  "name": "__testPackage",
  "types": "index.d.ts"
  ...
}

index.d.ts (library):

declare global {
  interface Array<T> {
    addRange<T>(elements: T[]): void;
    aggregate<U>(
      accumulator: (accum: U, value?: T, index?: number, list?: T[]) => any,
      initialValue?: U
    ): any;
  }
}

export const foo: number;

app.ts (client):

// if you remove the import, Array.prototype.addRange won't compile
import { foo } from "__testPackage";

console.log(foo); // 42

const arr = ["a", "b"];
arr.addRange(["c", "d"]); // compiles
console.log(arr); // [ 'a', 'b', 'c', 'd' ]
Sign up to request clarification or add additional context in comments.

1 Comment

Ok thanks, this is the way I went with: export const init = () => null;, then I can do import { init } from 'lib'; in the app.component.ts.
0

create a annonimous function that will add the extra features to the array and enclose it to () so you can call it.

example:

(function(){
   // add the extension methods here
})()

Then add it to the tsconfig.json or tsconfig.app.json in Angular 8 to the files

{
  ...
  "files": [
    // your extension path here,
    "src/main.ts",
    "src/polyfills.ts"
  ],
  ...
}

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.