saritha
saritha

Reputation: 659

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.

Upvotes: 0

Views: 1476

Answers (2)

Liu Lei
Liu Lei

Reputation: 1297

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);
    }
   },[])

Upvotes: 1

Adrian Brand
Adrian Brand

Reputation: 21658

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);

Upvotes: 0

Related Questions