Skip to content

Commit b82cffb

Browse files
fix(openapi-typescript): Stringify primitive constant values (#1149)
* fix(openapi-typescript): Stringify primitive constant values Closes #1118 * fixup! fix(openapi-typescript): Stringify primitive constant
1 parent 65ff4b1 commit b82cffb

File tree

4 files changed

+22
-8
lines changed

4 files changed

+22
-8
lines changed

.changeset/eighty-chairs-join.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"openapi-typescript": minor
3+
---
4+
5+
Stringify const values with no specified type

packages/openapi-typescript/src/transform/schema-object.ts

+1-7
Original file line numberDiff line numberDiff line change
@@ -41,13 +41,7 @@ export function defaultSchemaObjectTransform(schemaObject: SchemaObject | Refere
4141

4242
// const (valid for any type)
4343
if (schemaObject.const !== null && schemaObject.const !== undefined) {
44-
let schemaConst = schemaObject.const as any;
45-
if ("type" in schemaObject) {
46-
if (schemaObject.type === "string") {
47-
schemaConst = escStr(schemaConst);
48-
}
49-
}
50-
return transformSchemaObject(schemaConst, {
44+
return transformSchemaObject(escStr(schemaObject.const) as any, {
5145
path,
5246
ctx: { ...ctx, immutableTypes: false, indentLv: indentLv + 1 }, // note: guarantee readonly happens once, here
5347
});

packages/openapi-typescript/src/utils.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -257,7 +257,7 @@ export function tsUnionOf(...types: (string | number | boolean)[]): string {
257257

258258
/** escape string value */
259259
export function escStr(input: any): string {
260-
if (typeof input !== "string") return input;
260+
if (typeof input !== "string") return JSON.stringify(input);
261261
return `"${input.trim().replace(DOUBLE_QUOTE_RE, '\\"')}"`;
262262
}
263263

packages/openapi-typescript/test/schema-object.test.ts

+15
Original file line numberDiff line numberDiff line change
@@ -255,6 +255,21 @@ describe("Schema Object", () => {
255255
const generated = transformSchemaObject({ type: "string", const: "duck" }, options);
256256
expect(generated).toBe(`"duck"`);
257257
});
258+
259+
test("number", () => {
260+
const generated = transformSchemaObject({ type: "number", const: 42 }, options);
261+
expect(generated).toBe("42");
262+
});
263+
264+
test("string, no type specified", () => {
265+
const generated = transformSchemaObject({ const: "99" }, options);
266+
expect(generated).toBe(`"99"`);
267+
});
268+
269+
test("number, no type specified", () => {
270+
const generated = transformSchemaObject({ const: 300 }, options);
271+
expect(generated).toBe("300");
272+
});
258273
});
259274

260275
describe("polymorphic", () => {

0 commit comments

Comments
 (0)