TypeScript:如何扩展现有模块定义?

11

我有一个针对现有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>;
    ...
  }
}

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

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

但我仍然会出现一个错误,即“'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"
    ]
  }

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


你的代码中能否不使用标准的@types/mongoose?https://www.npmjs.com/package/@types/mongoose - paperball
1
@skyhavoc,它已经是@types/mongoose了。而且对我来说学习如何声明模块也很重要,不仅仅是使用它。 - Maxim
可能是因为你的 document 接口没有继承 interface Document extends MongooseDocument, NodeJS.EventEmitter, ModelProperties - hazardous
@hazardous 我尝试进行扩展,但是得到了相同的结果 - 错误。 - Maxim
3个回答

6

在我的情况下,我不得不使用reexport来合并声明。typescript 4.0.5

global-axios.d.ts:

export * from 'axios';

declare module 'axios' {
    export interface AxiosRequestConfig {
        myConfigOption?: boolean;
    }
}

1
太棒了!这对我也非常有效。需要为mixpanel添加一个缺失的类型。 - Stefanie

4

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

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

    "paths": {
        "mongoose": ["src/custom.d.ts"],
        "*": [
            "node_modules/*"
        ]
    }

1
定义Mongoose接口。
// types/mongoose/index.d.ts
declare module 'mongoose' {
  namespace Mongoose {
    export interface MyInterface {
      name: number;
    }
  }
}

使用
// app.ts
import mongoose, { Mongoose } from 'mongoose';
const a: Mongoose.MyInterface = {
  name: 122
};

我还在tsconfig文件中添加了"typeRoots": ["./node_modules/@types", "./server/types"],,这样做有帮助吗?

它没有起作用,但对我来说是一个不错的提示——去更改我的tsconfic文件。 - Maxim

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接