2017-02-16 37 views
1

我的使用情況:請求的RequestResponse type definition缺少body財產,是這樣的:如何加強在d.ts打字稿接口

declare namespace request { 

    // ... 

    export interface RequestResponse extends http.IncomingMessage { 
     request: Options; 
    } 

    // ... 

} 
declare var request: request.RequestAPI<request.Request, request.CoreOptions, request.RequiredUriUrl>; 
export = request; 

我試圖用類似創建request-fix.d.ts文件進行修復這個:

import * as http from 'http'; 
declare namespace request { 
    export interface RequestResponse extends http.IncomingMessage { 
     body: any; 
    } 
} 

但它沒有效果。我的最終目標是,在我的app.ts,我可以這樣做:

import * as rp from 'request-promise'; 
import { RequestResponse } from 'request'; 

let response = rp.get(url); 

response.statusCode; // works 
response.body; // doesn't compile 

當然,我可能只是有助於DefinitelyTyped :),但是這問題是關於以增強RequestResponse接口。

+0

1. request-fix.d.ts中的RequestResponse缺少'export' 2.是'tsconfig.json'中的'request'添加了request-fix.d.ts? – artem

+0

'.d.ts'文件即使在我廢話時也不會產生任何編譯時錯誤。在我的tsconfig.json中:'「files」:[「app.ts」,「request-fix.d.ts」]'。嘗試添加'///參考...>'我的app.ts,沒有區別。 – Borek

+0

哦'skipLibCheck'是真的。這讓我前進,至少我可以看到更多的錯誤.. – Borek

回答

6

這裏是在request-fix.d.ts作品組合:

import * as http from 'http'; 

declare module 'request' { 
    export interface RequestResponse extends http.IncomingMessage { 
     body: any; 
    } 
} 

增強現有模塊,declare module必須用來代替declare namespace,它必須編譯的源代碼中的某處出現在模塊範圍。

也就是說,request-fix.d.ts必須在頂層有一些導入才能將其轉換爲模塊,就像您在代碼中使用import * as http from 'http'一樣。如果declare module出現在非模塊範圍中(如我在答案中的第一次嘗試那樣),它只會聲明here所述的單獨的無關模塊。

+0

它不適合我。我已經創建了這個小回購來證明這個問題:https://github.com/borekb/ts-augmentation-demo – Borek

+0

導入必須在頂層,我已經用工作解決方案更新了GitHub演示:https: //github.com/borekb/ts-augmentation-demo。 (如果你更新你的代碼,我會將它標記爲答案。謝謝你的幫助!) – Borek

+0

是的,我剛剛找到相同的,更新的答案.. – artem

0

@artem是正確的+1,只是想補充一點,你不應該忘記命名空間。

例如,你這是怎麼從material-ui添加className道具的CardTitle組件:

declare module "material-ui" { 
    namespace __MaterialUI { 
     namespace Card { 
      export interface CardTitleProps { 
       className?: string; 
      } 
     } 
    } 
} 

的交代很簡單..模塊和命名空間只存在於運行時間,並自動合併。