相关文章推荐
苦恼的洋葱  ·  Gradle - Plugin: ...·  2 月前    · 
飘逸的萝卜  ·  setAlternateIconName ...·  6 月前    · 
光明磊落的铁链  ·  Re: [jetty-users] ...·  1 年前    · 
const Foo = () => { const [ value , setValue ] = React . useState (); return < input value = { value } onChange = {( e ) => setValue ( e . target . value )} / > const Foo = () => { const [ value , setValue ] = React . useState < string | undefined > (); return < input value = { value } onChange = {( e ) => setValue ( e . target . value )} / > const Foo = () => { const [ value , setValue ] = React . useState ( '' ); return < input value = { value } onChange = {( e ) => setValue ( e . target . value )} / >

The useState function has a generic parameter which we are not setting/declaring in the original case.

This leaves TypeScript to infer the generic type from the arguments given.

In this case useState() with no arguments, TypeScript infers the type as undefined .

TypeScript doesn't know that you later want to set a string into state here .

That is, leaving the generic parameter off is equivalent of doing:

const [value, setValue] = React.useState<undefined>(); 

The generic parameter determines the type of the value and setValue variables.

In this case, the setValue function is going to be the equivalent of:

function setValue(value: undefined) : void {

The input component doesn't like this, the event is creating has a target.value of type string.

So to solve this, we can either explicitly set the generic type, or be aware of when and how TypeScript is going to infer the generic type.

What do you think about providing Cypress and RTL selector and assertion functions alongside your components? #react #cypress #testing Type widening on strings #typescript What's going on with index types in TypeScript? #typescript

Built on Forem — the open source software that powers DEV and other inclusive communities.

Made with love and Ruby on Rails. DEV Community © 2016 - 2024.