【问题标题】:What is the datatype we will give for enum assigned variables?我们将为枚举分配的变量提供什么数据类型?
【发布时间】:2018-06-28 11:21:55
【问题描述】:

我必须在 typescript 或 angular 中使用什么数据类型来表示方向?填写那个XXXX。

注意:即使您没有提及数据类型或提及 any 数据类型,也不会出现错误。对于编码标准,我不想使用 any 数据类型。

enum Directions {
  Up,
  Down,
  Left,
  Right
}

let directions : xxxx = Directions;

【问题讨论】:

  • 如果不指定类型,则推断为typeof Directions
  • 如果你还想明确指定:let directions: typeof Directions
  • 所以我们是否必须给出类似“let direction: typeof Directions = Directions ?

标签: angular typescript enums


【解决方案1】:

只需使用枚举的名称作为类型,如in Typescript docs

enum Response {
    No = 0,
    Yes = 1,
}

function respond(recipient: string, message: Response): void {
    // ...
}

respond("Princess Caroline", Response.Yes)

【讨论】:

  • 我的场景不是这样的,我明确表示要写“让方向:xxxx =方向;”这样的语句
【解决方案2】:

感谢@Aleksey L. 的回答..

让方向:typeof Directions = Directions

【讨论】:

    猜你喜欢
    • 2013-11-19
    • 1970-01-01
    • 1970-01-01
    • 2010-10-09
    • 1970-01-01
    • 2014-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多