0

I have string enum declared as follows:

export namespace BootDeviceSelector {
    export const noChange: 'None' = 'None';
    export type noChange = 'None';
    export const PXE_ISCSI: 'Pxe' = 'Pxe';
    export type PXE_ISCSI = 'Pxe';
}
export type BootDeviceSelector = BootDeviceSelector.noChange | BootDeviceSelector.PXE_ISCSI;

In my application I have many more such a sets. I need a general mapping function which converts string (coming from backend) to value (example: "None" => BootDeviceSelector.noChange). I don't know how to declare parameters and output of function (maybe something better than any). I'd expect to pass to this function value to convert and list of values to search in - preferably as namespace name (example: BootDeviceSelector).

Or one-liner is good enough, something like this:

let a: BootDeviceSelector = (<any>BootDeviceSelector)['Pxe'];
console.log(a);

but here I've got undefined.

I'm using typescript 2.0.10 and Angular 2.3.1 but I can upgrade, although then I'll leave linting done by codelyzer package.

koral
  • 2,807
  • 3
  • 37
  • 65
  • But what's the point? `BootDeviceSelector.noChange` is `"None"`, and you already get `"None"`. – Nitzan Tomer Jan 12 '17 at 17:11
  • `"None"` comes from backend. In application I use `SomeObject.bootDeviceSelector: BootDeviceSelector` - class property of type `BootDeviceSelector` – koral Jan 12 '17 at 17:26
  • There's no difference between `let a = "None"` and `let a = BootDeviceSelector.noChange`. Trying to find the corresponding reference to `None` in `BootDeviceSelector` will gain you nothing as you'll end up with what you started with. – Nitzan Tomer Jan 12 '17 at 17:31

1 Answers1

0

Check the Reverse-Mapping for String Enums. Example:

enum BootDeviceSelector {
    noChange = <any>'None',
    PXE_ISCSI = <any>'Pxe'
}

let bds: BootDeviceSelector = BootDeviceSelector.PXE_ISCSI;
Rodris
  • 2,603
  • 1
  • 17
  • 25