javascript - typescript:如何扩展现有的模块定义?
我为现有的 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/' 目录下。
答案#1
在我的情况下,我不得不使用 reexport 来合并声明。 TypeScript 4.0.5
global-axios.d.ts:
export * from 'axios';
declare module 'axios' {
export interface AxiosRequestConfig {
myConfigOption?: boolean;
}
}
答案#2
好的!现在我知道这是 ts-node 的预期行为:https://github.com/TypeStrong/ts-node#missing-types
我已经在 tsconfig.json 中配置了路径设置,现在一切都正常工作了:
"paths": {
"mongoose": ["src/custom.d.ts"],
"*": [
"node_modules/*"
]
}
