简体   繁体   中英

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. These functions return the Response object they were called on to allow chaining (aka a fluent API).

I wish to add my own message function to do much the same. 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

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 :

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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