r.sendecky r.sendecky - 4 years ago 479
React JSX Question

Typescript: React event types

What is the correct type for React events. Initially I just used

any
for the sake of simplicity. Now, I am trying to clean things up and avoid use of
any
completely.

So in a simple form like this:

export interface LoginProps {
login: {
[k: string]: string | Function
uname: string
passw: string
logIn: Function
}
}
@inject('login') @observer
export class Login extends Component<LoginProps, {}> {
update = (e: React.SyntheticEvent<EventTarget>): void => {
this.props.login[e.target.name] = e.target.value
}
submit = (e: any): void => {
this.props.login.logIn()
e.preventDefault()
}
render() {
const { uname, passw } = this.props.login
return (
<div id='login' >
<form>
<input
placeholder='Username'
type="text"
name='uname'
value={uname}
onChange={this.update}
/>
<input
placeholder='Password'
type="password"
name='passw'
value={passw}
onChange={this.update}
/>
<button type="submit" onClick={this.submit} >
Submit
</button>
</form>
</div>
)
}
}


What type do I use here as event type?

React.SyntheticEvent<EventTarget>
does not seem to be working as I get an error that
name
and
value
do not exist on
target
.

More generalised answer for all events would be really appreciated.

Thanks

Answer Source

The SyntheticEvent interface is generic:

interface SyntheticEvent<T> {
    ...
    currentTarget: EventTarget & T;
    ...
}

And the currentTarget is an intersection of the generic constraint and EventTarget.
Also, since your events are caused by an input element you should use the FormEvent (in definition file, the react docs).

Should be:

update = (e: React.FormEvent<HTMLInputElement>): void => {
    this.props.login[e.currentTarget.name] = e.currentTarget.value
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download