Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript input onchange event.target.value

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'. 
like image 959
wildeyes Avatar asked Nov 18 '16 11:11

wildeyes


People also ask

How do you get events target value in TypeScript?

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.

How do you handle onChange event in TypeScript?

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.

What does onChange return?

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.

What is function of onChange form event?

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.


1 Answers

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; } 
like image 138
Yozi Avatar answered Oct 02 '22 21:10

Yozi