Reputation: 5992
I am passing @Input() element
variable to the app-child
component
<app-child [element]="element"></app-child>
element
is an object. It can be of many types, lets say Blue
, Red
or Green
Inside ChildComponent.ts
, how can I determine the type of element
and cast it to the correct type? instanceof
cannot be used with variables of type any
.
`ChildComponent.ts`
@Input() element: any; // is it of type Blue, Red or Green?
Upvotes: 1
Views: 1887
Reputation: 31
In Angular 16^ you can use transform option for @Input():
class ParentComponent {
data: Blue | Red | Green;
}
** parent template **
<app-child-component [data]="data" />
**
class ChildComponent {
// There is a simple cast function but you can do whatever you want
@Input({ transform: (v: Blue | Red | Green) => v as Green }) data!: Green;
}
docs: https://angular.dev/guide/components/inputs
Upvotes: 1
Reputation: 70564
First, if only Red, Blue and Green values are permitted, it might be clearer to declare element as such:
@Input() element: Red | Blue | Green;
How you can determine the type depends on what kind of types Red, Blue or Green are. If they are classes, you can use the trusty instanceof
operator:
if (this.element instanceof Red) {
const red: Red = this.element; // no cast necessary in if-block
}
If they are interfaces, that doesn't work because typescript interfaces do not survive transpilation to JavaScript. You can test a member though:
if ((<Red> this.element).reddishMember) {
const red = <Red> this.element;
}
Upvotes: 4