vega / ts-json-schema-generator

Generate JSON schema from your Typescript sources
MIT License
1.43k stars 191 forks source link

Add support for `SpreadElement` node type when resulting array is `ArrayLiteralExpression` #2055

Open gotenxds opened 2 weeks ago

gotenxds commented 2 weeks ago

Hi, when create an Array literal type the parser works fine as the resulting node is ArrayLiteralExpression That is, when creating something like so:

const myArr = ['a', 'b'] as const;

export interface MyInter {
   prop: (typeof myArr)[number];
}

but when combining two or more literalArrays into a new literal array the subNodeParser is finding a a SpreadElement for each array first.

const myArr = ['a', 'b'] as const;
const mySecondArr = ['c', 'd'] as const;
const myThirdArr = [...myArr, ...mySecondArr] as const;

export interface MyInter {
   prop: (typeof myThirdArr)[number];
}

I tried to create a custom parser for this but I'm not sure how to, as it need to return a type for each node where in this case I would want to return a single type for the entire array and not a type per spread operation.

Note: An alternative would be to create a type like so

const myArr = ['a', 'b'] as const;
const mySecondArr = ['c', 'd'] as const;

type ThirdArr = (typeof myArr | typeof mySecondArr)[number];

const myThirdArr: ThirdArr = [...myArr, ...mySecondArr] as const;

export interface MyInter {
   prop: ThirdArr;
}

Which would work but will result in a anyOf instead of an enum which I need for my usecase.

arthurfiorette commented 2 weeks ago

Hi, thanks for creating this issue! Want to open a PR for it? Remember to add unit tests :)

gotenxds commented 2 weeks ago

Hi @arthurfiorette, I'd love to but as I explained in the comment I tried to create a custom parser for this but I'm not sure how to tackle this one as it seems we get multiple nodes, one for each spread array instead of one node for the final array, if you have any idea how to tackle this one I'd be happy to finish it up including tests and open a PR