Notably, in TypeScript, an enum can only accept string or numeric values:
enum Stores {
STOREA = "amazon",
STOREB = "walmart"
}
However, if the functionality of an enum
is not necessary, a similar approach with object values can be implemented as demonstrated below:
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;
}
In this structure, there exist three representations of Stores
:
- An object at runtime with keys
STOREA
and STOREB
, each holding object values.
- A type reflecting the union of object values inside the
Stores
object.
- A namespace exposing its own types for easier access.
This implementation allows for emulating typical enum
behavior:
interface Foo {
store: Stores; // utilizing the type here
}
interface AmazonFoo extends Foo {
store: Stores.STOREA; // utilizing the namespace here
}
const foo: Foo = { store: Stores.STOREB }; // utilizing the value here
const amFoo: AmazonFoo = { store: Stores.STOREA }; // utilizing the value here
The compatibility of these uses applies to both versions of Stores
. Depending on specific requirements, certain features like the namespace may be omitted. The primary focus should align with actual use cases.
Interactive code playground link