Home > Mobile >  Conditional Interface - TS & Angular
Conditional Interface - TS & Angular

Time:09-19

I have a user component that has a variable named user: Employee | Student; In my HTML I have an element

{{ user.coure ?? user.department }}

Now I'm getting an error in my HTML since some properties in Employee are not available on Student interface. I don't want to use "any" type or have different variables e.g. student and employee. What is the best way?

Example of the interface that I'm using:

// user.interface.ts
export BaseUser {
    id: number;
    firstName: string;
    middleName: string;
}

export Employee extends BaseUser {
    department: string;
}

export Student extends BaseUser {
    course: string;
}

CodePudding user response:

You can use a custom type guard function

const isStudent = (user: Employee | Student): user is Student => {
  return "course" in user
}

const isEmployee = (user: Employee | Student): user is Employee => {
  return "department" in user
}

console.log(
  isStudent(user) ? user.course : user.department
)

You can use isStudent or isEmployee as you need. The compiler's control flow analysis will know that user is of type Student if isStudent returns true.

playground

  • Related