【问题标题】:Is it possible to store an enum that contains an object?是否可以存储包含对象的枚举?
【发布时间】:2020-12-04 20:35:30
【问题描述】:

我想创建一个像这样的枚举:

enum stores {
  STOREA = { label: "Amazon", value: "amazon" };
  STOREB = { label: "Walmart", value: "walmart" };
}

但我看到以下错误:

Type '{ label: string; value: string; }' is not assignable to type 'stores'.ts(2322)

这在打字稿中可能吗?

【问题讨论】:

    标签: typescript enums


    【解决方案1】:

    不,an enum 在 TypeScript 中只能接受字符串或数值:

    enum Stores {
        STOREA = "amazon", 
        STOREB = "walmart"
    }
    

    但您可能不需要enum 来获得相同或相似的功能,具体取决于您的用例。如果我想将Stores 变成具有尽可能像enum 的对象值的东西,我会这样写:

    const Stores = {
        STOREA: { label: "Amazon", value: "amazon" },
        STOREB: { label: "Walmart", value: "walmart" }
    } as const;
    type Stores = typeof Stores[keyof typeof Stores];
    namespace Stores {
        export type STOREA = typeof Stores.STOREA;
        export type STOREB = typeof Stores.STOREB;
    }
    

    这里有三个东西叫Stores:

    • 运行时存在的对象,具有键 STOREA 和 STOREB 以及对象值​​;
    • 对应于union对象值Stores对象内的类型;和
    • 一个暴露自己类型的命名空间,因此Stores.STOREA 类型是值Stores.STOREA 的类型,Stores.STOREB 类型是值Stores.STOREB 的类型。

    有了这些,你基本上可以做任何真正的enum 会为你做的事情:

    interface Foo {
        store: Stores; // using the type here
    }
    
    interface AmazonFoo extends Foo {
        store: Stores.STOREA; // using the namespace here
    }
    
    const foo: Foo = { store: Stores.STOREB }; // using the value here
    const amFoo: AmazonFoo = { store: Stores.STOREA }; // using the value here
    

    您可以验证这些用法是否适用于 Stores 的两个版本。当然,您的实际用例很可能不需要所有这些功能,在这种情况下,您只能包含您关心的那些。我的猜测是您绝对需要 const Stores = ... 对象,并且可能会使用 type Stores = .... 类型,但如果 namespace Stores { ... } 是必要的,我会有点惊讶。但同样,这取决于用例。

    Playground link to code

    【讨论】:

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