Skip to content

Commit

Permalink
Fix 'object' enumType types
Browse files Browse the repository at this point in the history
The enum types exported when using the 'object' enumType would always
just be a string, since the strings used in the enum object would be
widened to just be a 'string' type. This adds 'as const' to the
declaration, to prevent this widening.

See https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#const-assertions
  • Loading branch information
mogzol committed Aug 27, 2024
1 parent d7037db commit 704b819
Show file tree
Hide file tree
Showing 3 changed files with 5 additions and 5 deletions.
2 changes: 1 addition & 1 deletion generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ function getEnumTs(
case "object": {
const enumValues = enumData.values.map(({ name }) => ` ${name}: "${name}"`).join(",\n");
const enumName = enumNameMap.get(enumData.name);
return `export const ${enumName} = {\n${enumValues}\n};\n\nexport type ${enumName} = (typeof ${enumName})[keyof typeof ${enumName}];`;
return `export const ${enumName} = {\n${enumValues}\n} as const;\n\nexport type ${enumName} = (typeof ${enumName})[keyof typeof ${enumName}];`;
}
default:
throw new Error(`Unknown enumType: ${config.enumType}`);
Expand Down
4 changes: 2 additions & 2 deletions tests/options-behavior/expected/enumTypeObject.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ export const Gender = {
Male: "Male",
Female: "Female",
Other: "Other"
};
} as const;

export type Gender = (typeof Gender)[keyof typeof Gender];

Expand All @@ -13,7 +13,7 @@ export const DataTest = {
Banana: "Banana",
Orange: "Orange",
Pear: "Pear"
};
} as const;

export type DataTest = (typeof DataTest)[keyof typeof DataTest];

Expand Down
4 changes: 2 additions & 2 deletions tests/options-behavior/expected/enumTypeObjectPrefixSuffix.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ export const eGenderEnum = {
Male: "Male",
Female: "Female",
Other: "Other"
};
} as const;

export type eGenderEnum = (typeof eGenderEnum)[keyof typeof eGenderEnum];

Expand All @@ -13,7 +13,7 @@ export const eDataTestEnum = {
Banana: "Banana",
Orange: "Orange",
Pear: "Pear"
};
} as const;

export type eDataTestEnum = (typeof eDataTestEnum)[keyof typeof eDataTestEnum];

Expand Down

0 comments on commit 704b819

Please sign in to comment.