I recently faced difficulties using the JSTS library and its type bindings for Typescript and though in the end I made it work and I don't fully understand why.
I started off by installing JSTS and its bindings:
npm i --S jsts
npm i --D @types/jsts
Initially I tried the following in my code:
import jsts from 'jsts';
const {OL3Parser} = jsts.io;
const parser = new OL3Parser();
The above type-checked with no errors but crashed at runtime with: Uncaught TypeError: Cannot read property 'io' of undefined
.
Also, if I were to try to type the parser
variable in the above example as follows:
const parser: OL3Parser = new OL3Parser();
… then I would get:
TS2749: 'OL3Parser' refers to a value, but is being used as a type here. Did you mean 'typeof OL3Parser'?
I then tried:
import OL3Parser from 'jsts/org/locationtech/jts/io/OL3Parser';
This failed typechecking with:
TS7016: Could not find a declaration file for module 'jsts/org/locationtech/jts/io/OL3Parser'.
Following some online research I ended up with:
const jsts = require('jsts');
const parser: jsts.io.OL3Parser = new jsts.io.OL3Parser();
The above both type-checks and works as intended but I don't like the long qualified names and I don't understand why it is that I have to use the library in this particular way.
Any ideas?
You need to import jsts
as follows:
import * as jsts from 'jsts';
The reason for this is, that jsts
does rather export a namespace object instead of a named export or default export.
So using the above aproach imports the complete namespace of the module into a single variable, which than provides further access to various jsts
classes.
For example:
const reader = new jsts.io.GeoJSONReader();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With