Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions plugins/typescript/src/core/schemaToEnumDeclaration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,26 @@ describe("schemaToTypeAliasDeclaration", () => {
`);
});

it("should generate enums string (numbers)", () => {
const schema: SchemaObject = {
type: "integer",
enum: ["0", "00", "01", "1", "-1", "-01", "2", "3.33"],
};

expect(printSchema(schema)).toMatchInlineSnapshot(`
"export enum Test {
Zero = "0",
"00" = "00",
"01" = "01",
One = "1",
MinusOne = "-1",
"-01" = "-01",
Two = "2",
ThreePointThreeThree = "3.33"
}"
`);
});

it("should generate a int enum (using big numbers)", () => {
const schema: SchemaObject = {
type: "string",
Expand Down
6 changes: 5 additions & 1 deletion plugins/typescript/src/core/schemaToEnumDeclaration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,11 @@ function getEnumMembers(schema: SchemaObject): ts.EnumMember[] {
let enumValueNode: ts.Expression | undefined = undefined;

if (typeof enumValue === "string") {
enumName = enumValue;
if (String(Number(enumValue)) === enumValue) {
enumName = convertNumberToWord(Number(enumValue));
} else {
enumName = enumValue;
}
enumValueNode = f.createStringLiteral(enumValue);
} else if (typeof enumValue === "number") {
enumName = convertNumberToWord(enumValue)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,15 @@ describe("schemaToTypeAliasDeclaration", () => {
expect(printSchema(schema)).toBe(`export type Test = 1 | 2 | 3;`);
});

it("should generate enums string (numbers)", () => {
const schema: SchemaObject = {
type: "integer",
enum: ["1", "2", "3"],
};

expect(printSchema(schema)).toBe(`export type Test = "1" | "2" | "3";`);
});

it("should skip example which contains `*/` to avoid confusion", () => {
const schema: SchemaObject = {
title: "CronTimingCreate",
Expand Down
16 changes: 16 additions & 0 deletions plugins/typescript/src/utils/getEnumProperties.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,22 @@ const tens: string[] = [
];

export const convertNumberToWord = (n: number): string => {
if (n < 0) {
return "minus " + convertNumberToWord(-n);
}

if (!Number.isInteger(n)) {
const [intPart, fracPart] = n.toString().split(".");
return (
convertNumberToWord(Number(intPart)) +
" point " +
fracPart
.split("")
.map((digit) => ones[Number(digit)])
.join(" ")
);
}

if (n < 20) {
return ones[n];
}
Expand Down