I am using typescript with strict mode, we write index signature for interfaces something like this [key: string]: any but how should we write index signature for events like KeyboardEvent, follwing code getting error 'KeyboardEvent' has no index signature.ts(7017)

public checkInput(event: KeyboardEvent): void {
        if (event['keyIdentifier'] !== undefined) {
            keyCode = event['keyIdentifier'];
        }
    }

1 Answers

0
Titian Cernicova-Dragomir On Best Solutions

As the MDN entry states, this is a non-standard, deprecated feature:

The deprecated KeyboardEvent.keyIdentifier read-only property returns a "key identifier" string that can be used to determine what key was pressed. Its non-deprecated replacement is KeyboardEvent.key.

If you insist on using it, you can just cast keyIdentifier to an appropriate key of KeyboardEvent:

public checkInput(event: KeyboardEvent): void {
    if (event['keyIdentifier' as 'key'] !== undefined) {
        const keyCode = event['keyIdentifier' as 'key'];
    }
}

Other options are casting to any ((event as any)['keyIdentifier']) or augmenting the global type:

interface KeyboardEvent {
    keyIdentifier: string
}
class s {
    public checkInput(event: KeyboardEvent): void {
        if (event.keyIdentifier !== undefined) {
            const keyCode = event.keyIdentifier;
        }
    }
}