简体   繁体   中英

How to fix the error argument of type string or undefined is not assignable to parameter of type string using typescript and react?

i am getting error argument of type string or undefined is not assignable to parameter of type string using typescript and react

below is my code,

    function List({items}: Props) { 
        const [activeindex, setActiveindex] = React.useState<string>();
        return (
            items.map((item: any) => {
                <AddButton setActiveIndex={setActiveIndex} itemId={item.id}/>
            }
        );
    }

    
    interface AddButtonProps {
        setActiveIndex: any;
        itemId?: string;
    }
    function AddButton ({setActiveIndex, itemId}: AddButtonProps){
        const {toggleDrawing} = useDrawing();
        const handleClick = (itemId) => {
            setActiveIndex(itemId);
            toggleDrawing(itemId); //error here
        }
        return (
            <Button onClick={handleClick}/>
        );
    );


    function useDrawing () {
        const [editableItemId, setEditableItemId] = React.useState<string>();
        const toggleDrawing = React.useCallback(async (itemId: string) => {
            if (isDrawing && editableItemId === itemId) {
                cancelDrawing();
            } else if (isDrawing) {
                cancelDrawing();
                setEditableItemId(itemId);
            } else {
                setEditableWorkAreaId(itemId);
            }
        },
            [isDrawingPolygon, editableItemId, cancelDrawing]
    );
}

I am not sure why i am getting this error. could someone help me fix this. thanks.

try this way;)

const toggleDrawing = React.useCallback(async (itemId: string | undefined) => {
    if (isDrawing && editableItemId === itemId) {
        cancelDrawing();
    } else if (isDrawing) {
        cancelDrawing();
        setEditableItemId(itemId);
    } else {
        setEditableWorkAreaId(itemId);
    }
   },[])

You interface defines itemId?: string; and a string or undefined but the function call needs a string.

Use either

if (itemId) {
  toggleDrawing(itemId);
}

or

toggleDrawing(itemId || '');

or

toggleDrawing(itemId as string);

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