TypeScript interfaces are erased at runtime, so there is no instanceof for them. A pair of pure pipes can act as discriminators — each pipe checks for a unique property and returns the narrowed object or null, letting @if (... as typed) bind a properly-typed local in the template.
| ID | First name | Last name | Office number | Reason |
|---|---|---|---|---|
| 1 | A | B | 1 | |
| 2 | C | D | 2 | |
| 3 | E | F | passport | |
| 4 | G | H | 3 | |
| 5 | I | J | visum |
@if (person | asEmployee; as employee) {
<span>Office #{{ employee.officeNumber }}</span>
}
@if (person | asVisitor; as visitor) {
<span>Reason: {{ visitor.reason }}</span>
}
import { Pipe, PipeTransform } from '@angular/core';
interface Employee { officeNumber: number; }
interface Visitor { reason: string; }
@Pipe({ name: 'asEmployee' })
export class AsEmployeePipe implements PipeTransform {
transform(person: Employee | Visitor): Employee | null {
return 'officeNumber' in person ? person : null;
}
}
@Pipe({ name: 'asVisitor' })
export class AsVisitorPipe implements PipeTransform {
transform(person: Employee | Visitor): Visitor | null {
return 'reason' in person ? person : null;
}
}
Changing the counter binding does not trigger the pipe functions