2

Is it possible use Cytoscape UI extensions in Typescript? Layout extension can be used but when I need for example https://github.com/cytoscape/cytoscape.js-cxtmenu, I cant call function cy.cxtmenu( defaults ) because it isnt in cytoscape interface. Is there a way to use it?

My code in index.ts:

import cytoscape = require('cytoscape');
import contextMenus = require('cytoscape-cxtmenu');
cytoscape.use(contextMenus);

const cy = cytoscape({
    container: document.getElementById('cy'),
    ...
});
let defaults = {
     menuRadius: 100, 
     selector: 'node',
    //...
};

let menu = cy.cxtmenu( defaults );

To index.d.ts I add this declare:

declare module 'cytoscape-cxtmenu' {
    const ext: cytoscape.Ext;
    export = ext;
}

In console during transpilation I get this:

ERROR in [at-loader] ./src/index.ts:152:17
    TS2339: Property 'cxtmenu' does not exist on type 'Core'.
Luka.95
  • 21
  • 3

3 Answers3

0

Typescript is a superset of Javascript - and any code that will work as Javascript will work with Typescript.

The issue you are experiencing is a lack of proper Typescript definitions for the Javascript library you are using.

As far as I can see there are no typings for this package on DefinitelyTyped (https://github.com/DefinitelyTyped/DefinitelyTyped) - one option would be to write some and submit a pull request. Then you could install them as the npm package @types/cytoscape-cxtmenu after the request was merged and published (and include them as a file in your project until such a time)

Alternatively you could import the library as an any, eg:

const cxtmenu = require('cytoscape-cxtmenu');

This will mean that typescript will not perform any type checking on your interaction with that library.

Depending on how your typescript project is configured you may need to alternatively do something like this:

// @ts-ignore
import * as cxtmenu from "cytoscape-cxtmenu";
Michael
  • 2,189
  • 16
  • 23
0

Yes you can use. As Michael said typescript is super-set of JS. You can do anything that JS can do.

I'm using some other context menu extension with angular 8. import it like import * as contextMenus from 'cytoscape-context-menus';

If the library depends on some other js or css files, they must be added to angular.json file

canbax
  • 3,432
  • 1
  • 27
  • 44
0

You can use the as keyword (see this answer) to assign the type any to your Cytoscape instance, which should prevent the error from appearing. Taking the example in your question:

(cy as any).cxtmenu( defaults );

Please note that this is a hack. Assigning a type of any negates the benefits of Typescript and should be avoided, but I haven't found another solution.

Matt Saunders
  • 3,538
  • 2
  • 22
  • 30