Funn_Bobby
Funn_Bobby

Reputation: 715

How do I fix Typescript errors in OpenLayers 6.6.1

After upgrading to OpenLayers 6.6.1 I am receiving hundreds of typescript errors caused by generics.

For instance...

import olLayerVector from 'ol/layer/Vector';
import olFeature from 'ol/Feature';

public static highlightOverlay: olLayerVector = new olLayerVector({});
const selectedFeatures: Array<olFeature> = 
MapValues.highlightOverlay.getSource().getFeatures();

produces the errors

Generic type 'VectorLayer' requires 1 type argument(s)

Generic type 'Feature' requires 1 type argument(s).

Some threads I have read such as...

https://github.com/openlayers/openlayers/issues/8673

seem to indicate that using // @ts-ignore is a fix but this NOT a good solution to having your project riddled with typescript errors on generics.

Please tell me there is a better solution...any help is greatly appreciated

Upvotes: 1

Views: 4801

Answers (1)

tombags
tombags

Reputation: 31

I recently upgraded a large angular project to OpenLayers 6.6.1 and switched to using the OpenLayers generated typescript declaration files instead of using the @types/ol declaration files.

Both Feature and VectorLayer use generics, the former for the Geometry type, the later for the source type. One can avoid the 'Generic type 'Foo' requires 1 type argument(s)' errors by including the generics in your code as in the following example:

import { Feature } from 'ol';
import { Geometry } from 'ol/geom';
import { Vector } from 'ol/layer';
import { Vector as VectorSource } from 'ol/source';

// Typescript complains:
let f1: Feature = new Feature();
let vl1: Vector = new Vector({});

// Typescript is fine
let f2: Feature<Geometry> = new Feature<Geometry>();
let vl2: Vector<VectorSource<Geometry>> = new Vector<VectorSource<Geometry>>({});

VectorSource also uses a generic for its geometry type which is why the code needs Vector<VectorSource<Geometry>>

I did not need any type saftey on the Geometry type so I just used the super class Geometry. However, one could replace Geometry with something like Point if the Feature and source only contained Point geometry features.

The @types/ol declarations had defaults for the generics so one could avoid this syntax when using the older @types/ol declarations.

Upvotes: 3

Related Questions