Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs Typescript对象可能是';未定义';检查后_Reactjs_Typescript_React Beautiful Dnd_Immer.js - Fatal编程技术网

Reactjs Typescript对象可能是';未定义';检查后

Reactjs Typescript对象可能是';未定义';检查后,reactjs,typescript,react-beautiful-dnd,immer.js,Reactjs,Typescript,React Beautiful Dnd,Immer.js,快速提问-为什么Typescript仍然认为它将是未定义的 将下面的代码添加到我的应用程序中时,我在第draft.splice(result.destination.index,0,draggedItem)行出现Typescript错误表示结果。目标对象可能未定义。这部分是正确的,因为它的类型如下:DragUpdate.destination?:DraggableLocation | undefined。但是,我在这个函数的最开始做了一个检查,所以在给定的行中,它永远不会是未定义的 const

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

将下面的代码添加到我的应用程序中时,我在第
draft.splice(result.destination.index,0,draggedItem)行出现Typescript错误表示
结果。目标
对象可能未定义。这部分是正确的,因为它的类型如下:
DragUpdate.destination?:DraggableLocation | 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应用程序,还使用了
immer
React Beauty dnd
我无法对Alexsey L.说的话发表评论,但更快速的修复方法是直接使用!当您知道将定义某些内容时。

您使用的是回调和typescript不知道/不能保证
结果不会更改。快速修复-将
result.destination
提取到它自己的变量或使用非空断言运算符修复它,谢谢。也许这是一个快速修复,但您既没有解释其含义,也没有提供最小的示例。这称为非空断言运算符