[Fixed] Typechecking the observable subscribe parameter

Issue

What tsconfig is missing or why does the subscribe parameter not show an error or warning when defining the wrong parameter type.

As an example, the first is the correct Code. When I just have ‘user’ without the explicit typedef VS Code correctly identifies that user should be of type ‘UserDto’. But when I put another type in, say ‘AddressDto’, neither VS Code nor Typescript will complain that it’s the wrong type.

This is because they have at least one property in common. So if all Dtos have an ID, this error check is rendered useless. I hope to get a hint, that I’m not using the exact type for the user variable or something in that vein.

Is there a tsconfig option or a solution that enables this?

export interface UserDto { 
    id?: string;
    givenName?: string | null;
    surname?: string | null;
}

public onAcceptInvitation(): void {
    this.usersService.getSelf()
      .subscribe((user: UserDto): void => {
        Object.entries(user)
      });
  }

The ‘AddressDto’ has the property ‘id’. Therefore ‘AddressDto’ and ‘UserDto’ have at least one property in common and TS will accept this.

export interface AddressDto {
    id?: string;
    street?: string | null;
    houseNumber?: string | null;
}

public onAcceptInvitation(): void {
    this.usersService.getSelf()
      .subscribe((user: AddressDto): void => {
        Object.entries(user)
      });
  }

The Api Endpoint looks like this:

public getSelf(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'text/plain' | 'application/json' | 'text/json'}): Observable<UserDto> {
        return this.httpClient.get<UserDto>(`${this.configuration.basePath}/api/Users/self`,
            {
                responseType: <any>responseType,
                withCredentials: this.configuration.withCredentials,
                headers: headers,
                observe: observe,
                reportProgress: reportProgress
            }
        );
    }

Solution:
The problem lies in the Interface definition. If we have properties that are nullable, Typescript will accept the new type and will not show errors.

Solution

I don’t entirely understand what you are trying to achieve here, but hope i can help you.

neither VS Code nor Typescript will complain that it’s the wrong type

This is because in .subscribe((user: AddressDto)) you have already cast user into AddressDto, so ofc there will be no error.

when the API changes I want my frontend to fail the build

Ah, in that case the place you have to change is the getSelf() so that it will only return something specific.

For example:

public getSelf(): Observable<AddressDto> {
    return this.http.get<AddressDto>(`${API_URL}/getself`);
}

Leave a Reply

(*) Required, Your email will not be published