Brian Zengel
Brian Zengel

Reputation: 546

Typescript - when keeping comments inside object the code compiles in a strange way

I have a typescript file like this...

var obj = {
    /** Test comment */
    prop1: '',
    prop2: ''
};

And the javascript compiles as this...

var obj = {
    prop1: /** Test comment */
    '',
    prop2: ''
};

The problem with this is that JSDoc does not see the property of the object when generating documentation because the comment comes after the property.

My solution is this...

    var obj;
    obj = {};

    /** Test comment */
    obj.prop1 = '';

    obj.prop2 = '';

For some reason in this scenario I have to separate the declaration from the initialization, otherwise type script throws an error on the obj.propX = ''; lines of

The property 'propX' does not exist on value of type '{}'

My questions:

  1. Has anyone else run into this issue with the comment placement in objects?
  2. If so, how did you get around it if different than my own solution?
  3. If not, is there anything I can do to stop the error from happening so I can combine the variable declaration and the initialization.

Upvotes: 3

Views: 801

Answers (1)

Ryan Cavanaugh
Ryan Cavanaugh

Reputation: 221054

This is a bug. In a future release of TypeScript, the comments will be correctly preserved.

In the meantime, for a workaround, you have two options:

Either

var obj: any = {}; // No type checking, anywhere, on obj

Or

var obj: { prop1: string; prop2: string; } = {}; // More work, but type checking will happen now

After which you can do this and it should work as expected:

/** Test comment */
obj.prop1 = '';

Upvotes: 6

Related Questions