I’m trying to access the “code” property on a keyboard event but it isn’t there. I know it is available under the .nativeEvent property but can’t figure out how to use it. If I mouse over that type it shows as {...}. What is that?
I figured out one way to do it and it is kind of ugly. Is this the best way? It seems like this would be a place where I could use those types like Dom.keyboardEvent.
I think maybe what I’m looking for is some way to “cast” the native event to some other externally defined type, maybe the Dom.keyboardEvent, and then I can write a bunch of functions that work with that type.
The {..} is an object type without any clear definition of attributes. When a type like this pops up, you can use it pretty dynamically with the ["..."] accessor. It’s not your typical any though, because the type-checker will still keep track of how you use the object and locks in types as soon as it sees some concrete usage.
Yeah, you can do that, and you were already on the right track:
module NativeKeyboardEvent = {
type t
@get external getCode: t => string = "code"
external toNativeKeyboardEvent: {..} => t = "%identity"
}
let make = () => {
let onKeyDown = evt => {
evt->ReactEvent.Keyboard.preventDefault
let code =
evt
->ReactEvent.Keyboard.nativeEvent
->NativeKeyboardEvent.toNativeKeyboardEvent
->NativeKeyboardEvent.getCode
Js.log(code)
}
<div onKeyDown />
}