Yossi Sternlicht
Yossi Sternlicht

Reputation: 1030

Why isn't the key property recognised as part of the Event type in typescript

I have a function which finds out what button a user pressed using events, and uses the event.key property. However, in the parameter of the function, if i assign it a type Event, the compiler complains that

Property 'key' does not exist on type 'Event'.

Here is my code.

function getDirection(e:Event):void{
    let directionCode:number = e.key; 
    // code going on here
}

Why isnt the key property recognised on type event.

Upvotes: 29

Views: 23218

Answers (2)

Mostafa Mohammadzadeh
Mostafa Mohammadzadeh

Reputation: 911

You should type cast your event:

myInput.addEventListener('keyup', (e) => {
    let keyboardEvent = <KeyboardEvent> e;
    if(keyboardEvent.keyCode === 40){
        //...
    }
}

Also as the event.kecode is deprecated, you can do:

myInput.addEventListener('keyup', (e) => {
    let keyboardEvent = <KeyboardEvent> e;
    if(keyboardEvent.key === 'ArrowDown'){
        //...
    }
}

Upvotes: 1

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249686

Because Event does not have that property, KeyboardEvent is the class you want.

function getDirection(e:KeyboardEvent):void{
    let directionCode:number = e.keyCode; 
    let directionCodeStr:string = e.key; 
    // code going on here
}

Upvotes: 52

Related Questions