在TypeScript中使用字符串字面类型

3

我正在尝试使用一个(在Angular中的)方法,其定义如下:

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)

但是我遇到了这个错误:

错误 TS2345:类型为“{ headers: HttpHeaders; content: string; responseType: string; }”的参数不能赋值给类型“{ body?: any; headers?: HttpHeaders; params?: HttpParams; observe?: HttpObserve; reportProgress?:...}”的参数。属性“responseType”的类型不兼容。类型“string”不能赋值给类型“"text" | "json" | "arraybuffer" | "blob"”。

由于responseType没有像"type ResponseType = 'arraybuffer' | ..."这样的声明类型,我该如何将字面量'json'“转换”为此属性的有效值?
1个回答

8
你可以将字符串转换为字符串字面量类型:
let options = {
    headers: headers,
    content: content,
    responseType: 'json' as 'json'
};

编辑

从3.4版本开始,你也可以添加as const

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

谢谢,我也在 TypeScript 项目的讨论中找到了答案:https://github.com/Microsoft/TypeScript/issues/11465 - pablochacin
TypeScript 3.4 允许以下语法:'json' as const。对于重复特别是更复杂类型的情况会有所帮助。 - p4m
1
@p4m 这是真的。更新了答案,感谢你提出来,因为当我回答时 const 在 TS 中还不存在 :) - Titian Cernicova-Dragomir

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接