In my React web app, I have a number of react-dnd drop targets:
const DropTarget = () => {
const [{ canDrop, isOver }, drop] = useDrop(() => ({
accept: 'MyDnDItemType',
drop: () => ({ name: 'name of this drop target' })
}))
...
}
and items to drag around and drop in those targets:
const DraggableItem = () => {
const [{ isDragging }, drag] = useDrag({
type: 'MyDnDItemType'
})
...
When a DraggableItem is dropped into one of the DropTargets, I would like to get the drop target name. The react-dnd useDrag docs say in the end(item, monitor) section:
If [...] the drop target specified a drop result by returning a plain object from its
drop()method, it will be available asmonitor.getDropResult().
However, when I add an end(...) function in useDrag(...) and attempt to access the plain object returned, I get a TypeScript compiler error Object is of type 'unknown'.ts(2571).
const DraggableItem = () => {
const [{ isDragging }, drag] = useDrag({
end: (item, monitor) => {
const dropResult = monitor.getDropResult();
// console.log('dropResult:', dropResult)
// sample log output:
// dropResult: {dropEffect: 'move', name: 'name of this drop target'}
// PROBLEM: this fails to compile with
// Object is of type 'unknown'.ts(2571)
console.log('name:', dropResult.name)
},
type: 'MyDnDItemType'
})
...
I also tried end: (item, monitor: DragSourceMonitor) ... and, after reading about this somewhat related issue and delving into the source code, tried to use an explicit type:
type MyType = {
name: string;
};
const DraggableItem = () => {
const [{ isDragging }, drag] = useDrag({
end: (item, monitor: DragSourceMonitor<MyType>) => {
... (as above) ...
but the error persists.
How can I access the plain object returned by getDropResult() ?