簡體   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