Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using string literals types in Typescript

Tags:

typescript

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?

like image 621
pablochacin Avatar asked Dec 19 '25 20:12

pablochacin


1 Answers

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
};
like image 152
Titian Cernicova-Dragomir Avatar answered Dec 24 '25 12:12

Titian Cernicova-Dragomir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!