更新时间:2023-11-14 23:39:58
模块增强:
Typescript将此称为模块增强:您正在使用现有模块,并向其添加新定义.模块扩充具有自己的语法:
Typescript calls this a module augmentation: You are using an existing module and add new definitions to it. Module augmentations have their own syntax:
在文档之后,您的代码变为:
Following the docs, your code becomes this:
// file1.ts
import { Request as ExpressRequest, Response as ExpressResponse } from 'express';
// module name must be "express"
declare module 'express' {
// this can't be an export
const kvl : {
ValidationDone:(param:(error: any, response: ExpressResponse) => void) => void;
}
}
现在,您已经增强了express
模块并可以像这样使用它:
Now you have augmented the express
module and can use it like this:
// file2.ts
import {kvl} from "express";
// ...
模块化声明文件:
如果您不想将新类型注入express模块,则可以为新模块使用声明文件. 有多种类型,可以在此处找到很好的概述: https ://www.typescriptlang.org/docs/handbook/declaration-files/library-structures.html
If you don't want to inject your new types into the express module, you can use a declaration file for your new module. There are various types, a good overview can be found here: https://www.typescriptlang.org/docs/handbook/declaration-files/library-structures.html
基本上,您必须检查代码的使用方式,然后对它进行声明调整.在您的情况下,您似乎想将kvl
导入为模块.因此,您可以将自己放在此样本文件上: https://www.typescriptlang.org/docs/handbook/declaration-files/templates/module-d-ts.html
Basically, you have to check how the code is used and then adapt your declarations to that. In your case, it looks like you want to import kvl
as a module. So you can orient yourself on this sample file: https://www.typescriptlang.org/docs/handbook/declaration-files/templates/module-d-ts.html
我已将您的代码更改为适当的语法.顺便说一句,这仅在.d.ts文件中是正确的:
I have changed your code to the appropriate syntax. By the way, this is only correct in a .d.ts file:
//kvl.d.ts
import { Request as ExpressRequest, Response as ExpressResponse } from 'express';
export as namespace kvl;
export const kvl : {
ValidationDone:(param:(error: any, response: ExpressResponse) => void) => void;
};
实施模块:
如果kvl
是您自己的代码,则不必使用声明文件. Typescript可以分析您的模块.会产生具有正确类型的kvl常数的模块定义如下所示:
If kvl
is your own code, then you don't have to work with declaration files. Typescript can analyze your modules. A module definition that would produce a kvl constant with proper type could look like this:
// kvl.ts
import { Request as ExpressRequest, Response as ExpressResponse } from 'express';
export const kvl : {
ValidationDone:(param:(error: any, response: ExpressResponse) => void) => void;
} = {ValidationDone: function(param){}};
请注意,模块自动将其文件名作为模块名.因此,以上代码应位于名为kvl.ts的文件中.
Please note that modules automatically have their filename as modulename. Therefore, the above code should be in a file called kvl.ts.