问题
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'.
回答1:
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";
回答2:
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
来源:https://stackoverflow.com/questions/52449399/how-to-use-ui-extension-for-cytoscape-js-in-typescript