Search code examples
typescriptopenlayersopenlayers-6

where is SelectorEvent defined and how to import it for type-checking purposes?


I am using the below, standard (I assume) code to create a select interaction, add it on a map and take some actions when a feature is selected or deselected:

const select: Select = new Select({
  hitTolerance: 5,
  multi: false,
  condition: singleClick
});
this.map.addInteraction(select);


select.on('select', (se: SelectEvent) => {
  console.log('select fired: ', se);
  // do some stuff using se...
});

My problem is that I am using TypeScript and would like to take full advantage of type-checking but I can't figure out where to import SelectEvent from. So the above code fails type-checking with:

`TS2304: Cannot find name 'SelectEvent'`

When I try:

import {SelectEvent} from 'ol/interaction';

I get:

TS2305: Module '"../../../node_modules/@types/ol/interaction"' has no exported member 'SelectEvent'.

The open layers - relevant section of my package.json is:

$ npm ls --depth=0 | grep -i ol | grep -v polyfill
├── @siedlerchr/[email protected] (git+https://github.com/Siedlerchr/types-ol-ext.git#ec995982b2ba7aa4d415e67a350ec4b9f841ea37)
├── @types/[email protected]
├── [email protected]
├── [email protected]

Grepping for the SelectEvent type I found:

node_modules/@types/ol/interaction/Select.d.ts:declare class SelectEvent extends BaseEvent {

.. but it is not clear to me how to import this declaration (also it doesn't seem to even be exported to begin with).


Solution

  • As your grepping pointed out :

    node_modules/@types/ol/interaction/Select.d.ts:declare class SelectEvent extends BaseEvent 
    

    It is exported in node_modules/@types/ol/interaction/Select.d.ts :

        export class SelectEvent extends Event {
            constructor(type: SelectEventType, selected: Feature[],deselected: Feature[], mapBrowserEvent: MapBrowserEvent);
            deselected: Feature[];
            mapBrowserEvent: MapBrowserEvent;
            selected: Feature[];
        }
    

    So you just need to import it directly from there, like so :

    import { SelectEvent } from "ol/interaction/Select";
    

    This should fix your issue.

    By the way there is also an excellent support in another stack exchange community dedicated to all kind of spatial software engineering questions.