Open
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.