首页 文章

typescript - 将字符串转换为使用字符串枚举的值的常规函数

提问于
浏览
0

我有字符串枚举声明如下:

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;

在我的应用程序中,我有更多这样的集合 . 我需要一个通用的映射函数,它将字符串(来自后端)转换为值(例如: "None" => BootDeviceSelector.noChange ) . 我不知道如何声明函数的参数和输出(可能比 any 更好) . 我希望传递给这个函数值来转换和搜索的值列表 - 最好是命名空间名称(例如: BootDeviceSelector ) .

或者单线程就足够了,像这样:

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

但在这里我有 undefined .

我'm using typescript 2.0.10 and Angular 2.3.1 but I can upgrade, although then I'留下lip由 codelyzer 包完成 .

1 回答

  • 0

    检查Reverse-Mapping for String Enums . 例:

    enum BootDeviceSelector {
        noChange = <any>'None',
        PXE_ISCSI = <any>'Pxe'
    }
    
    let bds: BootDeviceSelector = BootDeviceSelector.PXE_ISCSI;
    

相关问题