【问题标题】:Can I default export constants and type alias from the same module?我可以从同一个模块默认导出常量和类型别名吗?
【发布时间】:2017-10-22 11:26:49
【问题描述】:

我有一个项目,其中包含许多包含常量字符串值的对象。

const StringLiterals = {
    a: "LetterA",
    b: "LetterB",
    c: "LetterC"
};

export default StringLiterals;

在很多情况下,这些字符串常量被用作参数。我想确保只使用这些常量中的字符串,所以我定义了一个类型别名。

type StringLiteral = keyof typeof StringLiterals;

现在,我必须在任何我想使用它的地方重新定义这个类型别名。我会在同一个模块中定义字符串值和类型别名,这样我就可以执行以下操作:

import StringLiteral from "./StringLiteral";

function doSomething(str: StringLiteral) {
    if (str === StringLiteral.a) { ... }
}

还有:

  • 我不想要两个不同的模块,一个包含类型,另一个包含字符串值。
  • 我不想要枚举,因为它们不允许您将标识符映射到字符串值;它们必须是数字。我还想避免大量引用数组来在字符串和数值之间进行转换。

这可能吗?

【问题讨论】:

    标签: typescript constants


    【解决方案1】:
    const StringLiterals = {
        a: "LetterA" as "LetterA",
        b: "LetterB" as "LetterB",
        c: "LetterC" as "LetterC"
    };
    
    type StringLiterals = (keyof StringLiterals)[keyof typeof StringLiterals];
    
    export default StringLiterals;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-26
      • 1970-01-01
      • 2022-07-10
      • 2022-06-25
      • 1970-01-01
      • 1970-01-01
      • 2021-07-02
      相关资源
      最近更新 更多