【问题标题】:Typescript Object is possibly 'undefined' after check检查后打字稿对象可能是“未定义”
【发布时间】:2021-01-19 11:14:39
【问题描述】:

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

将下面的代码添加到我的应用程序时,draft.splice(result.destination.index, 0, draggedItem); 线上出现 Typescript 错误,说 result.destination 对象可能未定义。这是部分正确的,因为它的类型如下: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

【问题讨论】:

  • 您正在使用回调和打字稿不知道/不能保证result 不会改变。快速修复 - 将result.destination 提取到自己的变量中或使用非空断言运算符

标签: reactjs typescript react-beautiful-dnd immer.js


【解决方案1】:

我无法评论 Alexsey L. 所说的话,但更快的解决方法是使用 !当您知道某些内容将被定义时。

【讨论】:

猜你喜欢
  • 2019-07-30
  • 2021-08-08
  • 2018-09-11
  • 2019-09-15
  • 1970-01-01
  • 1970-01-01
  • 2021-08-09
  • 2019-12-24
相关资源
最近更新 更多