使用仅扩展Array对象的库

时间:2019-09-03 15:49:26

标签: angular typescript npm

我有一个类型定义如下的库:

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;
    }
}

然后将该库导出到NPM包中,但是如何在另一个项目中使用它?

如果我尝试这样做:

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

我知道

Property 'addRange' does not exist on type

但是我不能仅仅导入addRange,因为它们是数组扩展名。

如何导入该库,以便Typescript知道它?

2 个答案:

答案 0 :(得分:1)

您通常在npm软件包的package.json types字段中公开类型。 如果这些类型包括全局类型扩充,则在客户端项目中需要该软件包时,编译器会自动选择它们。

package.json(库):

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

index.d.ts(库):

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(客户端):

// 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' ]

答案 1 :(得分:0)

创建一个匿名函数,该函数会将额外的功能添加到数组并将其括在()中,以便您可以调用它。

示例:

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

然后将其添加到Angular 8中的tsconfig.json或tsconfig.app.json中到文件

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