简体   繁体   中英

How to fix error argument of type undefined is not assignable to parameter of type 'string or () => string usng typescript and react?

i am getting error error argument of type undefined is not assignable to parameter of type 'string or () => string usng typescript and react.

below is my code,

export const useSomething =()=> {
    const [itemId, setItemId] = React.useState<string>(
        undefined //getting error here
    );
    const toggle = (itemId: string) => {
        setItemId(itemId);
        return {toggle, itemId};

    }
 }


 function  Parent() {
     const {itemId, toggle} = useSomething();
     return (
        <Child anotherId={anotherId} itemId={itemId} toggle={toggle}/>         
     );
 }


 function Child({itemId, anotherId, toggle) {
    return (
        <Button onClick={() => toggle(anotherId || '')/>
    );
 }

i am not sure what is causing this error.could someone help me with this. thanks.

You're setting the initial value of the state member to undefined , which isn't a string. So to fix it, you have to either:

  1. Initialize the state member with a string, instead of undefined ;

     const [itemId, setItemId] = React.useState<string>( "" // <=== or whatever string makes sense as the initial value );

    or

  2. Change the type of the state member to string | undefined string | undefined (a union type ), which allows the member to be a string or be undefined :

     const [itemId, setItemId] = React.useState<string | undefined>( undefined // −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^ );

Side note: If you're initializing to undefined , you can just leave the argument off entirely: = useState<string|undefined>() .

Since you initialize the state with undefined , the type of the state is not string but rather string | undefined string | undefined (this is a union type, meaning the value can either be string or undefined )

export const useSomething =()=> {
    const [itemId, setItemId] = React.useState<string | undefined>(
        undefined //getting error here
    );
    const toggle = (itemId: string) => {
        setItemId(itemId);
        return {toggle, itemId};

    }
 }

This may lead to errors in other places (where you expect a string, but not undefined is also an option but you should fix those to handle undefined

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