swagger-api / swagger-api/swagger-codegen
[TypeScript] String enums allow incorrect widening
Nobody has claimed this yet.
- Dominant language
- Mustache
- Stars
- 17.8k
- Forks
- 6k
- PR merge metrics
- No merged PRs in 30d
Description
Description
swagger-codegen emits TypeScript enums in the form of:
export namespace Foo {
export enum Bar {
baz = <any> "baz",
spam = <any> "spam"
}
}
This is a hack to support string-based enums, since TypeScript's built-in support for enums only support numbers. However, this workaround is extremely dangerous, since it allows incorrectly widening the enum value to the number type even though it is a string:
const x: number = Foo.Bar.baz; // this compiles, even though it shouldn't
const y: string = Foo.Bar.baz; // this does not compile, even though it should
Swagger-codegen version
As late as 55443da
Swagger declaration file content or url
Any declaration file containing a string enum
Command line used for generation
Any swagger-codegen invocation that generates TypeScript
Suggest a Fix
According to a TypeScript dev, since TS 2.1, you can safely write string-based enums without the builtin enum keyword. This approach has minimal overhead and exploits keyof, lookup types, and type inference.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Read modules/swagger-codegen/src/main/resources/typescript-node/api.mustache and the linked TypeScript guidance first. Update the generated string-enum representation so its values remain string-typed rather than widening to number, then verify a generated declaration accepts string assignment and rejects number assignment.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- tooling
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Clearly specified
- Newbie friendliness
- 35/100