Skip to content

Commit 697a2d0

Browse files
authored
feat: unions of enum's are rendered for properties for TS (#155)
1 parent b1f5e0c commit 697a2d0

File tree

3 files changed

+37
-0
lines changed

3 files changed

+37
-0
lines changed

src/generators/typescript/TypeScriptRenderer.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,9 @@ export abstract class TypeScriptRenderer extends AbstractRenderer<TypeScriptOpti
2323
if (Array.isArray(model)) {
2424
return model.map(t => this.renderType(t)).join(' | ');
2525
}
26+
if (model.enum !== undefined) {
27+
return model.enum.map(value => typeof value === 'string' ? `"${value}"` : value).join(' | ');
28+
}
2629
if (model.$ref !== undefined) {
2730
return model.$ref;
2831
}

test/generators/typescript/TypeScriptGenerator.spec.ts

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,36 @@ describe('TypeScriptGenerator', function() {
55
beforeEach(() => {
66
generator = new TypeScriptGenerator();
77
});
8+
test('should render union property type', async function() {
9+
const doc = {
10+
$id: "_address",
11+
type: "object",
12+
properties: {
13+
state: { type: "string", enum: ["Texas", "Alabama", "California", "other"] }
14+
}
15+
};
16+
const expected = `export class Address {
17+
private _state?: "Texas" | "Alabama" | "California" | "other";
18+
19+
constructor(input: {
20+
state?: "Texas" | "Alabama" | "California" | "other",
21+
}) {
22+
this._state = input.state;
23+
}
824
25+
get state(): "Texas" | "Alabama" | "California" | "other" | undefined { return this._state; }
26+
set state(state: "Texas" | "Alabama" | "California" | "other" | undefined) { this._state = state; }
27+
}`;
28+
29+
const inputModel = await generator.process(doc);
30+
const model = inputModel.models["_address"];
31+
32+
let classModel = await generator.renderClass(model, inputModel);
33+
expect(classModel).toEqual(expected);
34+
35+
classModel = await generator.render(model, inputModel);
36+
expect(classModel).toEqual(expected);
37+
});
938
test('should render `class` type', async function() {
1039
const doc = {
1140
$id: "_address",

test/generators/typescript/TypeScriptRenderer.spec.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,5 +34,10 @@ describe('TypeScriptRenderer', function() {
3434
model2.$ref = "ref2";
3535
expect(renderer.renderType([model1, model2])).toEqual('ref1 | ref2');
3636
});
37+
test('Should render enums', function() {
38+
const model = new CommonModel();
39+
model.enum = ["enum1", "enum2", 9];
40+
expect(renderer.renderType(model)).toEqual('"enum1" | "enum2" | 9');
41+
});
3742
});
3843
});

0 commit comments

Comments
 (0)