Kevin
Kevin

Reputation: 2257

How do you find the type of event in Typescript?

Here is my HTML template:

<input (keyup)="onKey($event)">

Here is my TypeScript file:

onKey(event: any) {
    console.log(typeof event);
}

The console.log outputs object but in reality it should be KeyboardEvent.

Is there a generic way to find the type of event?

Upvotes: 28

Views: 58756

Answers (1)

Aaron Beall
Aaron Beall

Reputation: 52143

You probably want to just check the event.type to see what it is, and infer the type from that.

Otherwise you could try using event instanceof KeyboardEvent or user-defined type guards.

Also, in your example you can just make the argument event:KeyboardEvent instead of event:any.

Upvotes: 31

Related Questions