【问题标题】:Typescript: Use `enum` values as `type`打字稿:使用“枚举”值作为“类型”
【发布时间】:2019-07-09 07:13:19
【问题描述】:

我想使用以下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

谢谢

【问题讨论】:

  • 能否请您在 stackblitz 上发布您的代码并详细说明您的问题?
  • @dileepkumar jami,我已经提供了尽可能多的描述。
  • @jcalz ,我更新了我的问题,请帮忙。

标签: typescript typescript-typings typescript3.0


【解决方案1】:

您可以使用 Enum 作为类型:

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

type SGenderOptions = "m/f" | "M/F" | "Male/Female"

export interface IGenderOptions {
  format: EGenderFormats | SGenderOptions;
}

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

const OTHER_DEFAULTS: IGenderOptions = {
  format: "M/F"
};

【讨论】:

  • 这样做不接受const DEFAULTS: IGenderOptions = { format: 'Male/Female' };
  • 我认为,如果您使用枚举强制执行格式选项,则有理由允许字符串输入。无论哪种方式,除非您使用联合类型,否则您不能同时拥有两个世界。我会用一个例子来更新答案。
  • 我们不能使用一些高级类型功能使用enuminterface 动态创建type 吗?我正在使用最新的 Typescript。
  • 我不明白你为什么坚持两种方式,我也找不到 TypeScript 方法来声明这种类型。
猜你喜欢
  • 2020-12-09
  • 1970-01-01
  • 2019-09-25
  • 2017-03-09
  • 1970-01-01
  • 2019-03-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多