0

I have a typescript enum generated via openapi-generator.

It looks like this:

export declare enum Role {
    SubscriptionOwner = "Subscription Owner",
    Admin = "Admin",
    Developer = "Developer",
    Publisher = "Publisher",
    Editor = "Editor"
}

I wanted to use it to generate select options, similar to below, taken from StackBlitz demo

import { Component } from '@angular/core';

export declare enum Symbols {
  equals = '\u003D',
  notEquals = '!='
}

@Component({
  selector: 'my-app',
  template: `
    <p>
      Having the symbol as label and name as value:
      <select>
        <option *ngFor="let symbol of keys(symbols)" [ngValue]="symbol">{{symbols[symbol]}}</option>
      </select>
    </p>
  `
})
export class AppComponent  {
  keys = Object.keys;
  symbols = Symbols;
}

However, when there's "declare", it's an ambient enum and that won't work. Once I remove "declare" it works, however since the enum is a generated source, I cannot edit it, it would get regenerated.

Is there some way I could convert the ambient enum in my consumer code to a normal enum, so I can generate the options? Or some other way to generate options from an ambient enum?

update

Okay, I learnt a bit about .d.ts files being simply headers for a code that exists elsewhere. I looked around and the generated library did include this:

var Role;
(function (Role) {
    Role["SubscriptionOwner"] = "Subscription Owner";
    Role["Admin"] = "Admin";
    Role["Developer"] = "Developer";
    Role["Publisher"] = "Publisher";
    Role["Editor"] = "Editor";
})(Role || (Role = {}));
;

So from reading this I understand this will prepare a Role object with those values privately. Why am I getting this error then though?

error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'typeof Role'.

when using

<option *ngFor="let role of keys(roles)" [ngValue]="role">{{roles[role]}}</option>
Ev0oD
  • 1,395
  • 16
  • 33
  • I sent a question on the ambience of the generated enum to the openapi-generator GitHub here: https://github.com/OpenAPITools/openapi-generator/issues/9867 , however, I read somewhere that a .d.ts file will consider those to be "declare"d implicitly even if you don't use the keyword – Ev0oD Jun 30 '21 at 10:16

1 Answers1

0

Okay, with more reading from here I found out that I can declare the index signature explicitly to be string and the values returned always being string. Since I know that to be true, because I am generating String enums and the declared Role.d.ts also clarifies that, I defined roles in the respective angular component as

roles: {[name: string] : string} = Role;

and after that, the compiler stopped complaining and the option generation works.

Ev0oD
  • 1,395
  • 16
  • 33