我有一个库,其类型定义如下:
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
,因为它们是数组扩展。
我如何导入这个库,这样打字本就知道了?
发布于 2019-09-03 14:00:25
通常在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' ]
发布于 2019-09-03 11:03:57
创建一个annonimous函数,将额外的特性添加到数组中,并将其封装到()中,以便您可以调用它。
示例:
(function(){
// add the extension methods here
})()
然后将其添加到tsconfig.json或tsconfig.app.json中的角8到文件中。
{
...
"files": [
// your extension path here,
"src/main.ts",
"src/polyfills.ts"
],
...
}
https://stackoverflow.com/questions/57775036
复制