Search code examples
javascriptangulartypescripthttpclientangular10

HttpClient, Make Action String Type Safe


Is there anyway to make the 'post' action string type safe below? Right now it accepts Any word to substitute in for 'post', example 'abcd', will Not create compilation error.

Example:

 saveUsers(body?: UpdateIdentityUserDto): Observable<any> {
    return this.httpClient.request<IdentityUserDtoBaseRequestResponse>('post',`${this.baseUserUrl}`,
        {
            body: body
        }
    );
  }

Option:

Here is another option below, however, I prefer to use string option above since those are auto generated from Swagger IO proxy generator.

saveUsers(body?: UpdateIdentityUserDto): Observable<any> {
    return this.httpClient.post<IdentityUserDtoBaseRequestResponse>(`${this.baseUserUrl}`,body);
}

Currently using Angular 10


Solution

  • I suggest wrapping it around and making it a generic method. Make a separate file for these generics.

    type HttpMethods = 'post' | 'get' | 'patch' | 'delete';
    
    request<T>(method: HttpMethods, body: any): Observable<any> {
        this.httpClient.request<T>(method, this.baseUrl, { body: body });
    }
    

    Then if you want to make a call an api call in a separate file, call this

    import { request } from '...'
    
    saveUsers(body?: BodyInterface): Observable<ResponseInterface> {
        return request<IdentityUserDtoBaseRequestResponse>('post', body)
    }