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

标签 typescript express

import { Request as ExpressRequest, Response as ExpressResponse } from 'express';
declare module 'kvl' {
    export = kvl;
}
declare const kvl: {
    ValidationDone:(param:(error: any, response: ExpressResponse) => void) => void;
}

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

我是在.d.ts里声明的,这样用不行吗?

最佳答案

模块增强:

Typescript 将此称为模块扩充:您正在使用现有模块并向其添加新定义。模块扩充有自己的语法:

  • 您声明的模块必须与扩充模块同名
  • 在模块内你不能导出任何东西

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

按照文档,你的代码变成这样:

// 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 模块并可以像这样使用它:

// file2.ts
import {kvl} from "express";

// ...

模块化声明文件:

如果您不想将新类型注入(inject)到 express 模块中,您可以为新模块使用声明文件。 有多种类型,可以在这里找到一个很好的概述: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

我已将您的代码更改为适当的语法。顺便说一句,这只在 .d.ts 文件中是正确的:

//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 常量的模块定义可能如下所示:

// 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 的文件中。

关于typescript - 模块扩充中不允许导出和导出分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53186841/

相关文章:

Angular 4 : Detect idle user using angular-user-idle

javascript - 尝试使用 jade 渲染 html 文件,但它仍然将其定位为 jade

javascript - WEB Socket 的 CORS 验证

node.js - ERR_HTTP_HEADERS_SENT : Cannot set headers after they are sent to the client at ServerResponse

node.js - 在 Nodejs 中加载静态资源

node.js - 在 express.js 上使用(和重用)多个 Mongoose 数据库连接

typescript - 在 VS Code 中,如何使用 Typescript 1.5 alpha 编译器

angular - 使用 setter 方法 ["set()"] 在 HttpParams 下

reactjs - react-select typescript 问题 - 通用类型 'ValueType' 需要 2 个类型参数。ts(2314)

reactjs - 更新到 create-react-app 4.0.0 后的 typescript 问题