gpt4 book ai didi

typescript - 是否可以存储包含对象的枚举?

转载 作者:行者123 更新时间:2023-12-04 03:45:55 26 4
gpt4 key购买 nike

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

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 中可能吗?

最佳答案

不,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 的东西:

  • 一个在运行时存在的对象,具有键 STOREASTOREB 以及对象值​​;
  • 对应于 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

关于typescript - 是否可以存储包含对象的枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65150373/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com