Search code examples
javascripttypescriptintellij-ideacss-selectorsyfiles

Migrating JavaScript to TypeScript


I am trying to migrate the following JavaScript Code into TypeScript.

var DemoGroupStyle = yfiles.lang.Class('DemoGroupStyle',{
  '$extends': yfiles.styles.NodeStyleBase,

  'constructor': function() {
    yfiles.styles.NodeStyleBase.call(this);
  },

  /**
   * Backing field for below property
   * @type {string}
   */
  '$cssClass': "",

  /**
   * Gets or sets a custom css class that is assigned to the top level element representing the node.
   * @type {string}
   */
  'cssClass': {
    '$meta': function() {
      return [
        yfiles.graphml.GraphMLAttribute().init({'defaultValue' : ""}),
        yfiles.lang.TypeAttribute(yfiles.lang.String.$class)];
    },
    'get': function() {
      return this.$cssClass;
    },
    'set': function(/**string*/ value) {
      this.$cssClass = value;
    }
  },

I tried out the following logic:

    cssClass: string = "";

    metacssClass() {
        return [new yfiles.graphml.GraphMLAttribute().defaultValue = "", new yfiles.lang.TypeAttribute(yfiles.lang.String.$class)];
    }

    getcssClass() {return this.cssClass;};

    setcssClass(value) {this.cssClass = value};

but it does not work if I want to use it in its place.

Can you please tell me why my logic is wrong and how I could change it?


Solution

  • If you depend onthe metadata stuff, then I'm afraid you won't be able to truely convert this class to a native TypeScript class. If you don't require the meta programming ("$meta") then you can easily translate this into TypeScript, roughly like so:

      class DemoGroupStyle extends yfiles.styles.NodeStyleBase {
    
        constructor() {
          super();
        }
    
        private $cssClass : string;
    
        get cssClass(): string {
            return this.$cssClass;
        }
    
        set cssClass(cssClass: string) {
            this.$cssClass = cssClass;
        }
      }
    

    However the $meta stuff won't work with TypeScript: See Extending Framework Classes and the secion about attributes.

    My suggestion is to keep this class as is using JavaScript syntax (it can easily be used in regular TypeScript code and coexists perfectly with native TypeScript and ES6 classes) and only convert those classes that don't require the use of meta attributes.