打字稿:如何扩展现有的模块定义?

Max*_*kin 5 javascript mongoose node.js typescript

我有一个为 extsting npm 包编写的声明文件,但似乎没有声明一种方法,我尝试声明它,但出现错误。请帮帮我。

现有 d.ts 文件的结构:

declare module "mongoose" {
...
  class Document {}
  interface Document extends MongooseDocument, NodeJS.EventEmitter, ModelProperties {
    increment(): this;
    remove(fn?: (err: any, product: this) => void): Promise<this>;
    ...
  }
}
Run Code Online (Sandbox Code Playgroud)

我尝试添加到接口 Document 方法 deleteOne。我的custom.d.ts:

declare module "mongoose" {
  interface Document {
    deleteOne(fn?: (err: any, product: this) => void): Promise<this>;
  }
}
Run Code Online (Sandbox Code Playgroud)

但我仍然收到错误“类型上不存在属性 'deleteOne'”。

如果您需要,这是我的 tsconfig.json:

{
    "compilerOptions": {
      "module": "commonjs",
      "removeComments": true,
      "esModuleInterop": true,
      "moduleResolution": "node",
      "allowJs": true,
      "allowSyntheticDefaultImports": true,
      "pretty": true,
      "resolveJsonModule": true,
      "sourceMap": true,
      "target": "ES2018",
      "outDir": "dist",
      "baseUrl": ".",
      "paths": {
          "*": [
              "node_modules/*"
          ]
      }
    },
    "include": [
      "src/**/*"
    ],
    "exclude": [
      "node_modules",
      "dist",
      "**/*.spec.ts"
    ]
  }
Run Code Online (Sandbox Code Playgroud)

我的 custom.d.ts 文件位于 'src/' 目录中。

d9k*_*d9k 9

在我的例子中,我必须使用重新导出来合并声明。打字稿 4.0.5

global-axios.d.ts

export * from 'axios';

declare module 'axios' {
    export interface AxiosRequestConfig {
        myConfigOption?: boolean;
    }
}
Run Code Online (Sandbox Code Playgroud)


Max*_*kin 4

好的!现在我知道这是 ts-node 的预期行为:https://github.com/TypeStrong/ts-node#missing-types

我已经在 tsconfig.json 中配置了路径设置,现在一切正常:

    "paths": {
        "mongoose": ["src/custom.d.ts"],
        "*": [
            "node_modules/*"
        ]
    }
Run Code Online (Sandbox Code Playgroud)