javascript - 使用 Fluent API 增强 Typescript

标签 javascript typescript

我有一些快速模块增强。我的意图是能够做到:

request.message('Hello').status(400).json({});

statusjson 函数是 Express Response 对象的一部分。这些函数返回调用它们的Response对象以允许链接(又名流畅的API)。

我希望添加自己的 message 函数来完成同样的事情。我的增强看起来像这样:

import { SomeType } from '...';

declare global {
    namespace Express {
        interface Response {
            // This works.  
            getSomeType(): SomeType;

            // This does not.  Typescript thinks the object returned here has ONLY the getSomeType/message functions on it
            message(str: string): Response; 
        }
    }

我尝试过

的变体
message(str: string): Express.Response

还有

message(str: string): Response & Express.Response

这没有什么区别。和以前一样:Typescript 认为这里返回的对象只有 getSomeType/message 函数

最佳答案

也许如果你这样写就会起作用:

import { SomeType } from '...';

declare namespace Express {
  export interface Response {
      getSomeType(): SomeType;
      message(str: string): Response; 
  }
}

Here是类似的问题

关于javascript - 使用 Fluent API 增强 Typescript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55228408/

相关文章:

entity-framework - 使用 Angular 2 时是否需要在 Typescript 中复制 Entity Framework 类?

javascript - 如何使用 FileReader 在 JavaScript 中读取大型视频文件?

javascript - 测试 onChange 处理程序时,React State 变得未定义

javascript - 我想让我的元素网站的#menu 按钮像开关一样工作

node.js - 安装 mocha 的 TypeScript 定义失败

javascript - 在 typescript 中遍历可变元组

TypeScript 无法在函数类型中派生类型约束

javascript - ng-repeat 按 $index 跟踪并从数组中删除元素

javascript - 设置 karma 来测试 node.js 模块?

angular - FirebaseError : Function DocumentReference. set() 调用了无效数据。不支持的字段值:未定义(在字段名称中找到)