swagger-api / swagger-api/swagger-codegen

[TypeScript] String enums allow incorrect widening

Open
#5,146 6 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Client: TypeScript Feature: Enum General: Discussion
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

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.