1

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?
10
  • What do you mean cast it? Could you give a less abstract illustration of the problem you're trying to solve? Commented Nov 26, 2017 at 22:31
  • I've added a ChildComponent.ts code. Commented Nov 26, 2017 at 22:35
  • That's not demonstrating any casting. As far as determining the type, have you read e.g. typescriptlang.org/docs/handbook/…? If it can be Blue, Red or Green why type it as any? You might as well not be using TS. Commented Nov 26, 2017 at 22:37
  • To what should it be typed then, if it can be Blue, Red or Green? See the problem? Commented Nov 26, 2017 at 22:40
  • 1
    "Union" types, yes; I suggest you read more of that page. Commented Nov 26, 2017 at 22:44

2 Answers 2

4

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.