Use HSBType in JSScripting with Typescript

I’m using OpenHAB 5.0.2 and I’m trying to convert some of my DSL Rules to JSScripting. I’m also using Typescript to get better syntax highlighting in my rules.

Now I would like to use the HSBType, but I only found examples for plain Javascript without Typescript. e.g. like this:

var HSBType = Java.type('org.openhab.core.library.types.HSBType');

I cannot find the “Java” type in the openhab-js library. Also there is no HSBType type in the library. Is there a way to use the HSBType with Typescript?

That’s because it’s not there. That line is importing the Java class. There is no JS version of that class.

I doubt it, but I’m no expert on Typescript. The openhab-js library does not create a proxy JS class for every openHAB Java class. So there will always be something.

@rlkoshak Thanks for the hint. I think I found a way to do this. I just created my own types for Java.type and HSBType. I’m also no Typescript expert, but it seems to work so far. Here are the types I’ve generated:

java.d.ts

declare namespace Java {
  function type<T extends { new (...args: any[]): any } = any>(className: string): T;
}

hsbtype.d.ts

declare namespace org.openhab.core.library.types {
  class HSBType {
    static KEY_HUE: string;
    static KEY_SATURATION: string;
    static KEY_BRIGHTNESS: string;

    static BLACK: HSBType;
    static WHITE: HSBType;
    static RED: HSBType;
    static GREEN: HSBType;
    static BLUE: HSBType;

    constructor();
    constructor(value: string);
    constructor(h: number, s: number, b: number);

    static valueOf(value: string): HSBType;
    static fromRGB(r: number, g: number, b: number): HSBType;
    static fromXY(x: number, y: number): HSBType;

    getHue(): number;
    getSaturation(): number;
    getBrightness(): number;

    getConstituents(): Map<string, number>;
    toRGB(): number[];
    toXY(): number[];
    getRed(): number;
    getGreen(): number;
    getBlue(): number;
    getRGB(): number;

    toString(): string;
    toFullString(): string;
    format(pattern: string): string;
    hashCode(): number;
    equals(obj: any): boolean;

    closeTo(other: HSBType, maxPercentage: number): boolean;

    as<T extends any>(target: { cast(obj: any): T }): T | null;
  }
}

Now I can use the Type like this:

export const HSBType = Java.type<typeof org.openhab.core.library.types.HSBType>(
  "org.openhab.core.library.types.HSBType"
);