0

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.

Linda Paiste
  • 38,446
  • 6
  • 64
  • 102
tommybernaciak
  • 390
  • 2
  • 17
  • 4
    You're using callback and typescript don't know/ can't guarantee that the `result` won't change. Quick fix - extract `result.destination` to its own variable or use non-null assertion operator – Aleksey L. Oct 04 '20 at 11:55

1 Answers1

0

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.

Dreamplay
  • 51
  • 9
  • Perhaps this is a quick fix, but you neither explained its implications, nor provided even the smallest example. – Aluan Haddad Oct 04 '20 at 12:42
  • 2
    This is called non-null assertion operator https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html#non-null-assertion-operator – Aleksey L. Oct 04 '20 at 13:07