Is there a way to add code completion or strong typing for objects with Typescript?
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?
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.