2017-09-18 148 views
2

我试图使用方法(在角),其具有以下定义:使用字符串文字类型的打字稿

request(method: string, url: string, options?: { 
    body?: any; 
    headers?: HttpHeaders; 
    params?: HttpParams; 
    observe?: HttpObserve; 
    reportProgress?: boolean; 
    responseType?: 'arraybuffer' | 'blob' | 'json' | 'text'; 
    withCredentials?: boolean; 
}): Observable<any>; 

我的代码如下所示:

let options = { 
    headers: headers, 
    content: content, 
    responseType: 'json' 
}; 

http.request(method, url, options) 

,但我得到这个错误:

error TS2345: Argument of type '{ headers: HttpHeaders; content: string; responseType: string; }' is not assignable to parameter of type '{ body?: any; headers?: HttpHeaders; params?: HttpParams; observe?: HttpObserve; reportProgress?:...'. Types of property 'responseType' are incompatible. Type 'string' is not assignable to type '"text" | "json" | "arraybuffer" | "blob"'.

由于reponseType没有一个声明的类型,如“类型的responseType =“一rraybuffer'| ...”,我怎么能‘投’字面‘JSON’是该物业的有效值

回答

3

,就可以把字符串到字符串字面类型:

let options = { 
    headers: headers, 
    content: content, 
    responseType: 'json' as 'json' 
}; 
+0

谢谢,我在讨论在打字稿项目中打开的问题时也找到了答案:https://github.com/Microsoft/TypeScript/issues/11465 – pablochacin