Definition file for mapbox-gl-draw in Typescript, also known as d.ts file

I attempted to define the mapbox-gl-draw project in a typed manner but unfortunately, I was unsuccessful. Can anyone provide some guidance on this?

Here is how the javascript file looks:

'use strict';

var Setup = require('./src/setup');
var Options = require('./src/options');
var API = require('./src/api');
const Constants = require('./src/constants');

var Draw = function(options) {
  options = Options(options);

  var ctx = {
    options: options
  };

  var api = API(ctx);
  ctx.api = api;

  var setup = Setup(ctx);
  api.addTo = setup.addTo;
  api.remove = setup.remove;
  api.types = Constants.types;
  api.options = options;

  return api;
};

module.exports = Draw;

window.mapboxgl = window.mapboxgl || {};
window.mapboxgl.Draw = Draw;

This is my index.d.ts file:

declare namespace mapboxgl {
    export function Draw(options?:any):any

}
declare module 'mapbox-gl-draw' {
    export = mapboxgl;
}

Answer №1

When dealing with this particular snippet of Javascript:

let map = new mapboxgl.Map({
  container: 'map',
  style: 'mapbox://styles/mapbox/streets-v8',
  center: [40, -74.50],
  zoom: 9
});

One approach would be to define mapOptions like so:

interface MapOptions {
 container?: string;
 style?: string,
 center?: number[];
 zoom?: number;
}


declare module "mapbox-gl-draw" {

}

Answer №2

The top recommendations for this extension can be found in the following GitHub issue:

https://github.com/mapbox/mapbox-gl-draw/issues/842

It remains a mystery why these suggestions have not been successfully submitted to DefinitelyTyped. Preserved below for future reference:

declare module '@mapbox/mapbox-gl-draw' {

import {Feature, FeatureCollection} from 'geojson'
  import {IControl} from 'mapbox-gl'
  import {IMapboxDrawControls} from '@mapbox/mapbox-gl-draw'

  namespace MapboxDraw {
    export interface IMapboxDrawControls {
      point?: boolean,
      line_string?: boolean,
      polygon?: boolean
      trash?: boolean,
      combine_features?: boolean,
      uncombine_features?: boolean
    }
  }

  class MapboxDraw implements IControl {

    getDefaultPosition: () => string

    constructor(options?: {
      displayControlsDefault?: boolean,
      keybindings?: boolean,
      touchEnabled?: boolean,
      boxSelect?: boolean,
      clickBuffer?: number,
      touchBuffer?: number,
      controls?: IMapboxDrawControls,
      styles?: object[],
      modes?: object,
      defaultMode?: string,
      userProperties?: boolean
    });

    public add(geojson: object): string[]

    public get(featureId: string): Feature | undefined

    public getFeatureIdsAt(point: { x: number, y: number }): string[]

    public getSelectedIds(): string[]

    public getSelected(): FeatureCollection

    public getSelectedPoints(): FeatureCollection

    public getAll(): FeatureCollection

    public delete(ids: string | string[]): this

    public deleteAll(): this

    public set(featureCollection: FeatureCollection): string[]

    public trash(): this

    public combineFeatures(): this

    public uncombineFeatures(): this

    public getMode(): string

    public changeMode(mode: string, options?: object): this

    public setFeatureProperty(featureId: string, property: string, value: any): this

    onAdd(map: mapboxgl.Map): HTMLElement

    onRemove(map: mapboxgl.Map): any

  }

  export = MapboxDraw
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What steps should I take to address the numerous errors I am encountering in Atom using the Atom linter tool?

My Atom interface is showing the following errors: {Error running gjslint}(x4) {Error running selective}(x4) Upon checking the errors section, I found the following details: [Linter] Error running selective Error: ENOENT: no such file or directory, open ...

What is the best way to export a ReactTS component along with its children?

After importing the component, I proceed to declare a new component which will be a child for the invoked one. import { someComponent } from './someComponent'; This is how I export it: const anotherComponent = () => {...}; export { someCompon ...

The arrow function in Jest is missing a name property

Currently, my setup includes: node.js: 9.8.0 Jest: 23.4.2 ts-jest: 23.1.3 typescript: 2.9.2 While attempting the following in my *.test.ts files: const foo = () => 'bar'; console.log(foo.name); // '' foo contains the name pro ...

Is there a way to insert data from one table into a MySQL Table in Drizzle and update the entry if it already exists?

My goal is to utilize Drizzle for inserting data into a table and updating it if the key already exists. In MySQL, the code would look like this: INSERT INTO myTable1(field1,field2,field3,field4) SELECT fieldOne,fieldTwo,fieldThree,fieldFour FROM myTable2 ...

Using TypeScript to wrap a class with a Proxy object

I've been working on a function that takes an API interface (I've provided a sample here) and creates a Proxy around it. This allows me to intercept calls to the API's methods, enabling logging, custom error handling, etc. I'm running i ...

What is the best way to implement forwardRef in a distinct select component?

Currently, I am utilizing react, typescript, and styled-components to work on my project. Specifically, I am aiming to create a select component for use in React Hook Form. Initially, everything seemed to be in order, but I encountered an error from typesc ...

Slate - developing a TypeScript function to filter and retrieve an object containing the highest property value

Check out this NEW RELATED QUESTION: I need to extract the largest number from a given object set. I am struggling with finding a solution. I have tried using max but I think my skills are lacking. Here is the code I have so far: @Function() pub ...

Struggling to solve a never-ending loop problem in a messaging application

I am currently in the process of developing a chat application. During the initialization of the chat page, I am checking for messages and storing them in an array. ngOnInit() { this.messageService.getMessages().doc(`${this.sortItineraries[0] + ...

Checking constructor arguments and code style issues

I need to ensure that the constructor parameter is validated correctly when an instance of a class is created. The parameter must be an object that contains exactly all the properties, with the appropriate types as specified in the class definition. If t ...

What are the steps to effectively troubleshoot TypeScript code in Visual Studio 2017?

Currently working on an ASP.NET Core project that heavily utilizes TypeScript. Does Visual Studio support debugging TypeScript code? ...

Ionic Vue is throwing an error indicating that a property is not found on the type '{ $route(currentRoute: any): void; }'

Currently, I am developing an Ionic WebApp using Vue and TypeScript. My current task involves retrieving the current id parsed by the route. To achieve this, I have been working on a watcher: export default { data() { return { ...

Invoke a function in Playwright exclusively when the test title includes a specific @tag

After years of utilizing Selenium, SpecFlow, NUnit, and other testing tools, I have recently delved into Playwright with TS. My goal is to interact with the AzureDevOps API to mark tests as automated only if they contain a specific tag in the test title (e ...

Showcasing a single object in an IONIC/Angular application using the ngIF directive

I am in need of assistance as I have encountered an issue. Essentially, I am fetching an object from an external API (Strapi) using the GET method, but when attempting to display it on Views with ngIF, it fails to show up. https://i.sstatic.net/nFyOE.png ...

Utilizing Typescript, create a customized dropdown with react-bootstrap for a tailored user

I've been working on incorporating a custom toggle drop-down feature based on the example provided on the react-bootstrap page, using Typescript and react functional components. Below is the code snippet for my component: import React from &apos ...

A guide on combining two native Record types in TypeScript

Is it possible to combine two predefined Record types in TypeScript? Consider the two Records below: var dictionary1 : Record<string, string []> ={ 'fruits' : ['apple','banana', 'cherry'], 'vegeta ...

Navigating between components in different modules using Angular 5

I have a home component within the homeModule and a contactUs component within the contactModule. When I click cancel on the contactUs component, it should redirect me to the Home component. Here are the routes: import {NgModule} from '@angular/cor ...

Is it possible to define a namespaced external module in TypeScript?

Currently, I am dealing with some legacy js modules that are either namespaced on window or define'd if the page is using AMD. Here's an example: // foo/bar.js (function (root, factory) { if (typeof define === "function" && define.am ...

Tips for configuring TypeScript in a monorepo to successfully compile private packages

I have configured a monorepo using turborepo that includes Nestjs for the backend and Nextjs for the frontend. To reuse prisma definitions, I separated them into their own package with its own tsconfig. In the index file of my database package where prism ...

Incorporate the pdfmake.js file into my TypeScript file

Working on a VSTS web extension and looking to utilize PDFmake.js to generate a pdf. The PDFmake.js file needs to be imported into the node_nodules folder by running npm install pdfmake. To import this JavaScript file into my TypeScript file, I'm fol ...

Understanding Express JS's handling of boolean values when reading them as strings

Using axios for communication between my React app and express API has presented an unexpected issue. Before sending the data, the value is identified as a boolean (as intended), but upon receival in the API, it gets converted to and stored as a string. T ...