I came across this piece of code:
interface Course {
code: string;
name: string;
user: number | {
id: number;
name: string;
};
}
This indicates that a course object can contain either the user object or the user key. When fetching the course from the backend using an HTTP request, the backend can potentially send either the user key or the user object as part of the course object. This is why the 'user' property is defined with such a type.
this.http.get<Course>('/api.course-endpoint/').subscribe(
response => {
const userId = response.user.id;
}
);
The line const userId = response.user.id;
in the above code snippet is resulting in an error.
Error TS2339: Property 'id' does not exist on type 'number | { id: number; name: string; }'.
Property 'id' does not exist on type 'number'.
How can this issue be resolved? And what is causing it to occur?