ts-json-schema-generator
ts-json-schema-generator copied to clipboard
description is purged if class attribute has a default value
ts-json-schema-generator appears to be bugged when generating schemas for classes.
For example:
export class Foo {
/** Whether or not foo has a bar. */
someAttribute: boolean;
}
This will correctly work to generate:
"someAttribute": {
"description": "Whether or not foo has a bar.",
"type": "boolean"
},
However, if we change it to have a default property like this:
export class Foo {
/** Whether or not foo has a bar. */
someAttribute = true;
}
The description value will be purged:
"someAttribute": {
"type": "boolean"
},
There was a recent pull request that added support for default values. Looks like it has a bug. Can you take a look?
I believe that was PR #1407.
I don't have the time to do a PR.
@swnf Can you take a look?
For a property with a type annotation, this project uses .parent to get the original PropertyDeclaration (and the corresponding JSDoc);
https://github.com/vega/ts-json-schema-generator/blob/ad97318c4dce2802b588e9bdb14b5059fc599cca/src/NodeParser/AnnotatedNodeParser.ts#L79-L80
I think getTypeAtLocation in my code is the problem:
https://github.com/vega/ts-json-schema-generator/blob/ad97318c4dce2802b588e9bdb14b5059fc599cca/src/NodeParser/InterfaceAndClassNodeParser.ts#L128-L131
It seems like the result of getTypeAtLocation does not have a reference to the PropertyDeclaration. Therefore, .parent on the resulting type is undefined.
I don't understand this project well enough to fix this properly. I'm not sure why AnnotatedNodeParser is invoked on the type node and not the PropertyDeclaration node (where the JSDoc is still available). It might also be possible to just assign .parent after typeToTypeNode. But I don't think the typescript API is supposed to be used like this. Unfortunately, I don't have more time to analyse this issue.
@domoritz Can you please take a look? This issue is blocking use of the schema generator with classes.
I don't have cycles but I could be happy to merge a pull request with a fix or a revert.
For those facing this issue, using the form id: string = "default"; works correctly. You may need to disable @typescript-eslint/no-inferrable-types.
For those facing this issue, using the form
id: string = "default";works correctly. You may need to disable@typescript-eslint/no-inferrable-types.
In my case, using v1.5.0, I couldn't manage to make it work, so I used this instead
/**
* Tax percentage
* @default 0
*/
tax: number;
This generated:
"tax": {
"type": "number",
"description": "Tax percentage",
"default": 0
},