I'm trying to write a properly typed callback function for the onKeyPress
event.
I've tried giving either the function or the event various types, but I can't seem to get the event e
to be recognized as having both the key
field and the target.value
field.
Case 1:
const onKeyPress: React.KeyboardEventHandler = async (e) => {
if (e.key === "Enter") {
console.log(e.target.value);
}
};
Message:
TS2339: Property 'value' does not exist on type 'EventTarget'.
Case 2:
const onKeyPress = async (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === "Enter") {
console.log(e.target.value);
}
};
Message:
TS2339: Property 'value' does not exist on type 'EventTarget'.
Case 3:
Turns out that even writing this simple JSX is going to throw out the same error:
<input type="text" onKeyPress={(e) => {
const key = e.key;
const val = e.target.value;
}}/>
Environment
From package.json
:
"@types/react": "^16.8.3"
"react": "^16.8.2"
"react-dom": "^16.8.2"
TypeScript 3.2.1
.
Any clue?
Update
Accepted answer led me to this working piece of code:
const onKeyPress = async (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === "Enter") {
console.log(`Received: ${e.currentTarget.value}`);
await doAsyncStuff(e.currentTarget.value);
}
};