【发布时间】:2021-03-31 23:19:22
【问题描述】:
我正在尝试解决编译器错误“对象可能是'未定义'”
const destinationColumnIndex = (): number => {
if (typeof result.destination === 'undefined') {
return 0;
}
return boardData.findIndex(
(column) => column.id === Number(result.destination.droppableId)
);
};
但是打字稿编译器仍然告诉我“result.destination”可能是未定义的。
我也试过了:
if (result.destination === undefined) {
return 0;
}
和:
if (!result.destination) {
return 0;
}
和:
if (!result || typeof result.destination === 'undefined') {
return 0;
}
没有任何效果。甚至认为这可能是一些错误,所以我重新启动了 VS Code,但仍然存在相同的错误。
编辑 - 更多代码:
const onDragEnd = async (result: DropResult) => {
if (!result.destination) {
return;
}
const sourceColumnIndex = (): number =>
boardData.findIndex(
(column) => column.id === Number(result.source.droppableId)
);
const destinationColumnIndex = (): number => {
if (typeof result === 'undefined' || result.destination === undefined) {
return 0;
}
return boardData.findIndex(
(column) => column.id === Number(result.destination.droppableId)
);
};
react 组件内部的函数
【问题讨论】:
-
它说的是哪个对象?
-
它强调'result.destiantion'
-
if(result?.destination === 'undefined') -
它说“此条件将始终返回 'false',因为类型 'DraggableLocation | undefined' 和 'string' 没有重叠。”当我做 if(typeof result?.destination === 'undefined') 和以前一样的错误时。
标签: javascript typescript