Skip to content

const is output as single value enum when inferStringEnumKeysFromValues: true #666

@rmobis

Description

@rmobis

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions