Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 861
Kevin Avatar asked Mar 05 '16 21:03

Kevin


People also ask

What is the type of event TypeScript?

Events supported are: AnimationEvent , ChangeEvent , ClipboardEvent , CompositionEvent , DragEvent , FocusEvent , FormEvent , KeyboardEvent , MouseEvent , PointerEvent , TouchEvent , TransitionEvent , WheelEvent .

How do you know what type of event?

Correct Option: D. getID() can be used to determine the type of an event.

What is the type of click event in TypeScript?

The onClick event occurs when an element is clicked. This element can be a button, a div element, an image, etc. This article walks you through a couple of different examples of handling the onClick event in a React app that is written in TypeScript.

What is the data type of React event?

React events are written in camelCase syntax: onClick instead of onclick . React event handlers are written inside curly braces: onClick={shoot} instead of onClick="shoot()" .


1 Answers

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.

like image 163
Aaron Beall Avatar answered Sep 18 '22 13:09

Aaron Beall