0

快速提问 - 为什么 Typescript 仍然认为它是未定义的?

将下面的代码添加到我的应用程序时,我在线上有 Typescript 错误,draft.splice(result.destination.index, 0, draggedItem);result.destinationObject 可能未定义。这是部分正确的,因为它的类型如下:DragUpdate.destination?: DraggableLocation | undefined. 但是,我在此函数的最开始进行了检查,因此在给定的行中它永远不会是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;
            })
        );
    }, []);

这是带有钩子的 React 应用程序,也使用immerreact-beautiful-dnd.

4

1 回答 1

0

我无法评论 Alexsey L. 所说的,但更快的解决方法就是使用 ! 当你知道某些东西会被定义时。

于 2020-10-04T12:16:47.143 回答