node-java icon indicating copy to clipboard operation
node-java copied to clipboard

Is there a way to add code completion or strong typing for objects with Typescript?

Open velara3 opened this issue 1 year ago • 1 comments

I'm using this project in a nodejs project in vscode using Typescript..

I've got it to work with a custom class / jar / library and now I'm wondering if there's a way to add strong typing or code completion in vscode.

For example, I have the following working code:

var java = require("java");
java.classpath.push("pngLibrary.jar");
const PngColorType = java.import("com.fileformats.png.PngColorType");
var colorType = new PngColorType();

But if I type the variable like so:

var java = require("java");
java.classpath.push("pngLibrary.jar");
const PngColorType = java.import("com.fileformats.png.PngColorType");
var colorType: PngColorType = new PngColorType(); // error here

I get the following error:

'PngColorType' refers to a value, but is being used as a type here. Did you mean 'typeof PngColorType'? ts(2749)
---
type PngColorType = /*unresolved*/ any

Is there any support for strong typing, code completion and so on?

velara3 avatar May 01 '24 20:05 velara3

Not that I am aware of but there are a few tools out there that generate .d.ts files from a Java source. You could try to use one of those to generate typings for your projects and get type-checking support.

Your other option is to do it manually like I do. This also helps to keep track of where JS and Java mix as anything I do not add to this list will throw an error.


export namespace JavaClasses {
  export interface JavaClass {
    (...args: unknown[]): any;
    new (...args: unknown[]): any;
    [key: string]: any;
  }

  /* eslint-disable @typescript-eslint/no-empty-interface */
  export interface Foo extends JavaClass {}

  export interface File extends JavaClass {
    getParentFile(): JavaClasses.File;
    getAbsolutePath(): string;
  }
}

// Somewhere in your code
return java.import("java.io.File") as JavaClasses.File;

Definitely not a perfect solution. Did the trick for me.

lm-sousa avatar May 10 '24 10:05 lm-sousa