【问题标题】:Workaround for string based enums in typescript打字稿中基于字符串的枚举的解决方法
【发布时间】:2016-06-15 15:12:19
【问题描述】:

所以我发现了一个建议,即在 typescript 中,您可以使用以下语法创建基于字符串的枚举:

export enum TextAlign {
    Left = <any>"start",
    Right = <any>"end",
    Center = <any>"middle"
}

使用这种方法有什么缺点吗?

有一个建议是使用字符串文字类型,虽然我发现枚举更舒服,因为你可以遍历值。

【问题讨论】:

  • stackoverflow.com/q/15490560/215552 上的答案有很多关于使用基于字符串的枚举的细节。你的问题被那些人回答了吗?此外,您似乎不是在寻求解决方法,正如您的标题所暗示的那样,而是有什么缺点。

标签: typescript


【解决方案1】:

使用这种方法有什么缺点吗?

安全

let x:number = TextAlign.Left; // compiles fine but actually you just assigned a string to number

更多

每次你断言你都可能对编译器撒谎:https://basarat.gitbooks.io/typescript/content/docs/types/type-assertion.html 这些谎言往往会迎头赶上:)

更多更多

通常首选字符串文字类型:https://basarat.gitbooks.io/typescript/docs/types/literal-types.html

【讨论】:

    猜你喜欢
    • 2017-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-23
    • 2022-06-11
    • 2016-10-09
    • 1970-01-01
    • 2020-02-24
    相关资源
    最近更新 更多