快速提问 - 为什么 Typescript 仍然认为它是未定义的?
将下面的代码添加到我的应用程序时,我在线上有 Typescript 错误,draft.splice(result.destination.index, 0, draggedItem);
说result.destination
Object 可能未定义。这是部分正确的,因为它的类型如下: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 应用程序,也使用immer
和react-beautiful-dnd
.