What types should I provide for HttpRequest in my interceptor on angular 10 on strict mode

Viewed 324

I've been working on strict mode on Angular 10 which comes with the "no-any" tslint rule. I've fixed almost everything on my app to not contain the any type, but I don't know which types I can provide in my interceptor for the HttpRequest and HttpEvent.

I assume there could be quite a few types, I've been looking for examples of this online, but they are mostly old examples who use any.

For example: I have many post requests, all of them pass different objects in the body to the server. I understand that the <T> (any) in the HttpRequest represents the body. Should I create a type variable with all the given objects? It seems messy.

import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { AuthService } from '../services/auth.service';
import { catchError } from 'rxjs/operators';

@Injectable()
export class JwtInterceptor implements HttpInterceptor {
  constructor(private authService: AuthService) { }

  intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    const token = this.authService.getToken();
    request = request.clone({
      setHeaders: {
        Authorization: `Bearer ${token}`,
      },
    });
    return next.handle(request).pipe(
      catchError((err) => {
        if (err.status !== 200) {
          this.authService.logout();
        }
        return throwError(err);
      })
    );
  }
}
1 Answers

I usually stick to unknown.

Another (and maybe prettier) solution might be defining a special union type, or a common interface.

export type ManyTypes = Type1 | Type2 | Type3; or whatever types you might want to use.

Related