打字稿:使用“枚举”值作为“类型”

时间:2019-02-15 07:14:36

标签: typescript typescript-typings typescript3.0

我想使用以下enum的值:

export enum GenFormats {
    SHORT_LOWER = 'm/f', SHORT_UPPER = 'M/F', FULL = 'Male/Female'
};

如下所示:

export interface IGenderOptions {
    format: 'm/f' | 'M/F' | 'Male/Female'
};

通过使用类型提取/定义类似:

{{some type cast/logic}}<GenFormats>    // Outputs: 'm/f' | 'M/F' | 'Male/Female'

更新的问题:

这是我的代码:

export enum EGenderFormats {
    SHORT_LOWER = 'm/f', SHORT_UPPER = 'M/F', FULL = 'Male/Female'
};

export interface IGenderFormats {
    SHORT_LOWER: 'm/f'; SHORT_UPPER: 'M/F'; FULL: 'Male/Female';
};

export interface IGenderOptions {
    format: IGenderFormats[keyof IGenderFormats]
};

const DEFAULTS: IGenderOptions = {
    format: EGenderFormats.FULL
};

我的问题是,如何使用enum EGenderFormatsinterface IGenderFormats而不是两者的单个实体?

我正在使用Typescript 3.2.2

谢谢

1 个答案:

答案 0 :(得分:2)

您可以将枚举用作类型:

%userprofile%\appdata\local\Microsoft\VisualStudio\15.0_a26f780e\ProjectAssemblies