3
votes

I'm trying to use an method (in Angular) that has the following definition:

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>;

My code looks like this:

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

 http.request(method, url, options)

But I get this error:

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"'.

As reponseType doesn't have a declared type like "type ResponseType = 'arraybuffer' | ...", how can I "cast" the literal 'json' to be a valid value for this property?

1

1 Answers

7
votes

You can cast the string to the string literal type:

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

Edit

Since 3.4 you could also add as const:

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