futurGH/ts-to-jsdoc

Careful with class property declarations - diverging behaviour

Closed this issue · 2 comments

Given TS code:

class Frame {
  bias: number;
  constructor() {
    this.bias = 0.001;
  }
}
class Multiframe extends Frame {
  bias: number;
}
const frame = new Frame();
const multiframe = new Multiframe();
console.log('frame.bias', frame.bias);
console.log('multiframe.bias', multiframe.bias);

And tsc compiles into this JS:

"use strict";
class Frame {
    constructor() {
        this.bias = 0.001;
    }
}
class Multiframe extends Frame {
}
const frame = new Frame();
const multiframe = new Multiframe();
console.log('frame.bias', frame.bias);
console.log('multiframe.bias', multiframe.bias);

Output:

image

However, ts-to-jsdoc transpiles into:

class Frame {
    bias = undefined;
    constructor() {
        this.bias = 0.001;
    }
}
/** @extends Frame */
class Multiframe extends Frame {
    bias = undefined;
}
const frame = new Frame();
const multiframe = new Multiframe();
console.log('frame.bias', frame.bias);
console.log('multiframe.bias', multiframe.bias);

Output:

image

It's a combination of useDefineForClassFields, which is true by default but likely false in your project, producing

class Frame {
    bias;
}

and

ts-to-jsdoc/index.ts

Lines 230 to 232 in 64f2176

if (!classPropertyNode.getStructure()?.initializer) {
classPropertyNode.setInitializer("undefined");
}

I'm not entirely sure why I had that check in the first place, going to see if it needs tweaking.

Fixed in 2.0.0!