Reputation: 117
I'm trying to solve compiler error " Object is possibly 'undefined' "
const destinationColumnIndex = (): number => {
if (typeof result.destination === 'undefined') {
return 0;
}
return boardData.findIndex(
(column) => column.id === Number(result.destination.droppableId)
);
};
but typescript compiler still tells me that "result.destination" may be undefined.
I have tried also:
if (result.destination === undefined) {
return 0;
}
and:
if (!result.destination) {
return 0;
}
and:
if (!result || typeof result.destination === 'undefined') {
return 0;
}
and nothing works. Even thought it may be some bug so i restarted VS Code but there are still the same error.
EDIT - MORE 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)
);
};
it's function inside of react component
Upvotes: 0
Views: 3964
Reputation: 1561
You should just do:
if (result === undefined || result?.destination === undefined) {
return 0;
}
Checking typeof
is not a good way to check for undefined.
or
if (!result || result?.destination === undefined) {
return 0;
}
UPDATE
try this:
const onDragEnd = (result: DropResult) => {
if (!result || !result.destination) {
return;
}
const sourceColumnIndex = (): number =>
boardData.findIndex(
(column) => column.id === Number(result.source?.droppableId)
);
const destinationColumnIndex = (): number => {
if (!result || !result.destination) {
return 0;
}
return boardData.findIndex(
(column) => column.id === Number(result.destination?.droppableId)
);
};
}
Upvotes: 1