In my react and typescript app, I use: onChange={(e) => data.motto = (e.target as any).value}
.
How do I correctly define the typings for the class, so I wouldn't have to hack my way around the type system with any
?
export interface InputProps extends React.HTMLProps<Input> { ... } export class Input extends React.Component<InputProps, {}> { }
If I put target: { value: string };
I get :
ERROR in [default] /react-onsenui.d.ts:87:18 Interface 'InputProps' incorrectly extends interface 'HTMLProps<Input>'. Types of property 'target' are incompatible. Type '{ value: string; }' is not assignable to type 'string'.
Use a type assertion to type event. target in TypeScript, e.g. const target = event. target as HTMLInputElement . Once typed correctly, you can access any element-specific properties on the target variable.
To type the onChange event of an element in React, set its type to React. ChangeEvent<HTMLInputElement> . The ChangeEvent type has a target property which refers to the element. The element's value can be accessed on event.
An onChange event handler returns a Synthetic Event object which contains useful meta data such as the target input's id, name, and current value.
The onchange attribute fires the moment when the value of the element is changed. Tip: This event is similar to the oninput event. The difference is that the oninput event occurs immediately after the value of an element has changed, while onchange occurs when the element loses focus.
Generally event handlers should use e.currentTarget.value
, e.g.:
onChange = (e: React.FormEvent<HTMLInputElement>) => { const newValue = e.currentTarget.value; }
You can read why it so here (Revert "Make SyntheticEvent.target generic, not SyntheticEvent.currentTarget.").
UPD: As mentioned by @roger-gusmao ChangeEvent
more suitable for typing form events.
onChange = (e: React.ChangeEvent<HTMLInputElement>)=> { const newValue = e.target.value; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With