简体   繁体   English

使用流畅的API进行打字稿扩充

[英]Typescript augmentation with fluent API

I have some express module augmentations. 我有一些快速模块增强。 My intention is to be able to do: 我的意图是能够做到:

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

The status and json functions are part of the express Response object. statusjson函数是快速Response对象的一部分。 These functions return the Response object they were called on to allow chaining (aka a fluent API). 这些函数返回被调用以允许链接(也称为流利的API)的Response对象。

I wish to add my own message function to do much the same. 我希望添加自己的message功能以执行相同的操作。 My augmentation looks like so: 我的扩充看起来像这样:

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; 
        }
    }

I've tried variations of 我试过了

message(str: string): Express.Response

And

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

This made no difference. 这没什么区别。 As before: Typescript thinks the object returned here has ONLY the getSomeType/message functions on it 如前所述:Typescript认为此处返回的对象仅具有getSomeType / message函数

Maybe if you write like this it will be work: 也许如果您这样写就可以了:

import { SomeType } from '...';

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

Here was similar question 是类似的问题

Ok, found the solution. 好的,找到解决方案。 I needed to import express into my type augmentation, and make my augmentation return express.Response : 我需要将express导入我的类型扩充中,并使扩充返回express.Response

import { SomeType } from '...';
import express from 'express';

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM