3

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 Answer 1

8

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
};
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, I just also found the answer in the discussion of the issue open at the typescript project: github.com/Microsoft/TypeScript/issues/11465
TypeScript 3.4 allows the following syntax: 'json' as const. Helps with the repetition, especially for more complex types.
@p4m That is true. Updated the answer, thank you for bringing it up, as const was not in TS when I gave this answer :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.