Mapbox-gl typing won't allow accessToken assignment

Here's a temporary workaround I've been using:

Object.getOwnPropertyDescriptor(mapboxgl, "accessToken").set('YOUR_TOKEN');

Explanation

Since the object was redefined to use a custom setter which places the token inside an internal closure - we can call the setter function directly as shown in the example.

Diving a little deeper, we can see that es6 modules are constants by definition: https://github.com/Microsoft/TypeScript/issues/6751#issuecomment-177114001

we can then do something like: (mapboxgl as any).accessToken = ... which will work.


For those finding this now ... You don't even need to set the Mapbox accessToken this way, it can be passed in as an option (since v1.2)

const map = new mapboxgl.Map({
  accessToken: '...',
  container: '...',
  style: '...',
});

Pity it's not the method used in any of the examples (yet).

Docs: https://docs.mapbox.com/mapbox-gl-js/api/#map

1.2 release notes: https://github.com/mapbox/mapbox-gl-js/releases/tag/v1.2.0

PR that adds it: https://github.com/mapbox/mapbox-gl-js/pull/8364


You can also use this format:

(mapboxgl as typeof mapboxgl).accessToken = ...