json-schema-to-typescript icon indicating copy to clipboard operation
json-schema-to-typescript copied to clipboard

`const` is output as single value enum when `inferStringEnumKeysFromValues: true`

Open rmobis opened this issue 5 months ago • 0 comments

When transforming a schema with the const property and inferStringEnumKeysFromValues: true, the constant type is output as a single value enum. This can be an issue because it obfuscates the underlying type. It's specially troublesome when using anyOf with a constant field to disambiguate the object, such as in the second example.

Minimal Example

Schema

{
	"type": "string",
	"const": "foo"
}

Expected Output

export type Root = 'foo';

Actual Output

export const enum Root {
	foo = 'foo'
}
Second Example

Schema

{
	"type": "object",
	"anyOf": [
		{
			"properties": {
				"type": {
					"type": "string",
					"const": "a"
				},
				"foo": {
					"type": "number"
				}
			}
		},
		{
			"properties": {
				"type": {
					"type": "string",
					"const": "b"
				},
				"bar": {
					"type": "number"
				}
			}
		}
	]
}

Expected Output

export type Root =
	| {
			type?: 'a';
			foo?: number;
	  }
	| {
			type?: 'b';
			bar?: number;
	  };

Actual Output

export type Root =
	| {
			type?: Type;
			foo?: number;
	  }
	| {
			type?: Type1;
			bar?: number;
	  };

export const enum Type {
	a = 'a'
}
export const enum Type1 {
	a = 'b'
}

From what I understand, this is due to a normalization where internally schemas with const are transformed to single value enum, likely for easier handling later? And because I have inferStringEnumKeysFromValues set to true, it automatically outputs the enum type for everything it thinks is an enum.

If this is something you agree should be fixed, I'd be willing to work on a PR, just let me know.

rmobis avatar Jul 21 '25 14:07 rmobis