繁体   English   中英

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

[英]Typescript augmentation with fluent API

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

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

statusjson函数是快速Response对象的一部分。 这些函数返回被调用以允许链接(也称为流利的API)的Response对象。

我希望添加自己的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; 
  }
}

是类似的问题

好的,找到解决方案。 我需要将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