Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using the JSTS library type bindings for TypeScript

Tags:

typescript

jts

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?

like image 804
Marcus Junius Brutus Avatar asked Aug 30 '25 17:08

Marcus Junius Brutus


1 Answers

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();
like image 85
Sebastian Frey Avatar answered Sep 02 '25 10:09

Sebastian Frey