Quick question - why Typescript still thinks it will be undefined?
When added code below to my application I have Typescript Error on line draft.splice(result.destination.index, 0, draggedItem);
saying that result.destination
Object is possibly undefined. This is partially true as it is typed like this: DragUpdate.destination?: DraggableLocation | undefined
. However, I do a check at the very beginning of this function so at a given line it will never be undefined
.
const onDragEnd = useCallback((result: DropResult) => {
// do nothing if no destination
if (!result.destination) return;
setState((prevState: IOrderCard[]) =>
produce(prevState, draft => {
const draggedItem = draft[result.source.index];
draft.splice(result.source.index, 1);
draft.splice(result.destination.index, 0, draggedItem);
return draft;
})
);
}, []);
This is React app with hooks, using also immer
and react-beautiful-dnd
.
I can't comment to what Alexsey L. said but an even quicker fix is to just use ! when you know something will be defined.