Home > Enterprise >  How to set type of variable on useState using typescript?
How to set type of variable on useState using typescript?

Time:04-27

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'.

CodePudding user response:

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('');
  • Related