Mohammad Hossein Amri
Mohammad Hossein Amri

Reputation: 1985

Angular typecast $event

I am trying to apply fix the issues by enabling the strict mode and one of the issue I faced that I don't have a clean answer for that is when $event is unknown

<div
     echarts
     (chartInit)="onChartInit($event)"
     (chartLegendSelectChanged)="onChartLegendSelectChanged($event)"
     (chartRendered)="onChartRender($event)"
></div>

here I have 3 methods that is returning unknown,

enter image description here

but refering to the document for example in onChartLegendSelectChanged I know that it return a LegendOption

so I define the method like this:

onChartLegendSelectChanged($event: LegendOption) {
    //logic when chart legend selected
}

while this is correct and typescript is happy about it, angular isn't happy with it and expect the method definition be type of unknown

while I can change the function argument to unknown and inside the function I cast the type to the desired type, but it's very ugly.

so is there anyway to cast the $event to a type inside the template? i saw other solution use pipe, but you can't use pipe inside a method call.

Upvotes: 1

Views: 1167

Answers (2)

sandrooco
sandrooco

Reputation: 8716

I'd say you have to provide a type for the @Output:

  @Output() chartLegendSelectChanged = new EventEmitter<LegendOption>();

This way you can maintain type safety (which isn't the case with $any).

Upvotes: 2

Eli Porush
Eli Porush

Reputation: 1547

You can use $any() function in template.

In your case: (chartLegendSelectChanged)="onChartLegendSelectChanged($any($event))"

it's basically declare it as any type :)

Upvotes: 2

Related Questions