Skip to content

Typescript: Why not use string-literal types to represent enums of type string? #6206

Closed
@bedag-moo

Description

@bedag-moo
Description

The typescript-angular2 generator currently emits enums in the form

    export enum StatusEnum {
        Open = <any> 'open',
        InProgress = <any> 'inProgress',
        Resolved = <any> 'resolved',
        Closed = <any> 'closed'
    }

For enums of type string the translation

    type StatusEnum = "open" | "inProgress" | "resolved" | "closed";

would be more type-safe (witness #5146), and more flexible to use. For instance, I could do:

    const badgeType: {[K: StatusEnum]: string} = {
        open: "danger",
        inProgress: "warning",
        resolved: "info",
        closed: "success",
    }

rather than

    const badgeType = <any>{}; // no type safety, because I can not enumerate the enum values
    badgeType[StatusEnum.Open] = "danger";
    badgeType[StatusEnum.InProgress] = "warning";
    badgeType[StatusEnum.Resolved] = "info";
    badgeType[StatusEnum.Closed] = "success";

as well as directly refer to enum constants in an angular template:

<div [ngSwitch]="issue.state">
  <div *ngSwitchCase="'open'"> 

rather than an unnecessary indirection in the template

<div [ngSwitch]="issue.state">
  <div *ngSwitchCase="StatusEnum.Open"> 

over the component

import { StatusEnum} from ...

export class MyComponent {
  StatusEnum = StatusEnum;
}

to the imported enum.

Swagger-codegen version

master

Suggest a fix/enhancement

Generate enums of type string as union of string literals, leaving enums of numeric type as they are (they need special treatment anyway to fix #3500).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions