且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

模块扩充中不允许导出和导出分配

更新时间: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:

  • 您声明的模块必须与扩展模块具有相同的名称
  • 在模块内,您什么都无法导出

这在这里描述: https://github.com/Microsoft/TypeScript-Handbook/blob/fa9e2be1024014fe923d44b1b69d315e8347e444/pages/Declaration%20Merging.md#module-augmentation

在文档之后,您的代码变为:

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.