Search code examples
typescripttypes

How to conditionally change the type in typescript in angular?


I am making an angular component dependent on the API Response. I am getting these from an API Response.

  1. When there's no error

    Data : { Status: string; Data: number; }

  2. When there's an Error I am getting this.

    Data : { Status: string; Error: string; Message: string; }

As we can see Status is common I tried implementing this.

interface ApiModel {
  Status: string;
}

interface DataModel extends ApiModel {
  Data: number;
}
interface ErrorModel extends ApiModel {
  ErrorCode: string;
  Message: string;
}

I am trying to use the typescript to give it my variable an option where it can be either one and then pass that type in it's response too.

I don't want to use optional type here hence I am facing these issues.

What I am expecting is,

if (typeof Response === DataModel){
Response: DataModel;
// Other code
}
else {
Response:ErrorModel;
// Other code
}

The API call here

getReminder(reminderId: number) {
    const API_URL = `${this.BASE_URL}users/${this.userId}/reminders/${reminderId}`;
    return this.httpClient.get<ErrorModel | DataModel>(API_URL, this.options).pipe(
      map((data: ErrorModel | DataModel) => {
        return data;
      })
    );
  }

Solution

  • After going through all the above answers I came to the conclusion that conditionally altering the interface is possible in TS but not possible in angular components. Hence,

    interface ApiModel {
    Status: string;
    Data?: string;
    ErrorCode?: string;
    Message?: string;
    }
    

    Although this might seem like a cheaper or a much simpler version, I was targeting this.

    Alternatively, Using Class also works. There I can define conditional type as in a class there's logic that can be used but if we are to use interface then the above solution is much simpler and easy to use.