简体   繁体   中英

How to set type of variable on useState using typescript?

I created a variable named text and a hook named setText. I'm using it to change the value of a form input field.

How could I set that text will be of type string?

Here's what I did try:

interface TextInterface {
  text: string | null,
  setText: (value: string) => void,
}

const [ text, setText ] = useState<TextInterface>('');

But when doing it the following error is displayed: Argument of type 'string' is not assignable to parameter of type 'TextInterface | (() => TextInterface)'.

It also display errors inside the input field and inside the handleText function (used on onchange inside input field).

The function:

const handleText = (e: React.FocusEvent<HTMLInputElement>): void => {
    setText(e.currentTarget.value);
}

That displays the error: Argument of type 'string' is not assignable to parameter of type 'SetStateAction'

The input field:

<input type="text" value={ text } onChange={ handleText } />

Error:Type 'TextInterface' is not assignable to type 'string | number | readonly string[] | undefined'.

const [ text, setText ] = useState<TextInterface>('');

You're close, but the useState generic doesn't expect you to pass in a type that describes both the state and the state-setter. You just need to specify the type of the state, as in:

const [ text, setText ] = useState<string | null>('');

If null wasn't a possibility, you could also leave off the explicit type, and typescript would infer the type to be string

const [ text, setText ] = useState('');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM