I'm making an Angular Application which is sending calls to API. This is one of methods from AuthService (responsible for authenticating user):
login(loginForm: UserLoginRequest): Observable<AuthenticationResponse | TfaResponse> {
return this.http.post<AuthenticationResponse | TfaResponse>('api/auth/login', loginForm);
}
This methods return an Observable with one of following responses:
export class AuthenticationResponse {
token: string;
refreshToken: string;
}
export class TfaResponse {
requiresTwoFactor: boolean;
isTwoFactorConfigured: boolean;
}
Then I subscribe on this Observable in my component and I want to do different actions in dependence of type of response:
this.authService.login(userLoginForm)
.subscribe(
(result) => {
// type of result is AuthenticationResponse
if (*type check*) {
// action with AuthenticationResponse
}
// type of result is TfaResponse
else if (*type check*) {
// action with TfaResponse
}
},
);
At the moment I'm just checking if object owns some properties from this class, like this:
this.authService.login(userLoginForm)
.subscribe(
(result) => {
if ('token' in result) {
// action with AuthenticationResponse
}
else if ('requiresTwoFactor' in result) {
// action with TfaResponse
}
},
);
But I understand that's a definitely bad solution which will broke up after first change in AuthenticationResponse or TfaResponse class. How should I check class in this case?
if ('token' in result)seems like a perfectly acceptable solution to me? Though you shoukd really be usinghasOwnPropertynotin- Liam