Can an enum be used to store an object?

I am trying to define an enum like:

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

However, I encountered the following error message:

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

Does anyone know if this is possible in typescript?

Answer №1

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Challenges with namespace and require("uniqid") in Typescript when using @types/uniqid

Upon adding @types/uniqid using the command npm install --save @types/uniqid to utilize in a class, I encountered an issue when trying to instantiate this class with new. If I include import uniqid = require("uniqid"); at the beginning of the page to use ...

Matching packages with mismatched @types in Webpack 2: A comprehensive guide

Having trouble implementing SoundJS (from the createJS framework) in my TypeScript project using webpack 2. In my vendors.ts file, I have the following import: import "soundjs"; Among other successful imports. The @types definitions installed via npm a ...

Issue with default date not functioning in Primeng's p-calendar module

I'm having trouble setting a default date in the datepicker. I attempted to use the defaultDate property of p-calendar, here's what I did: <p-calendar placeholder="mm/dd/yyyy" name="deadline" required [(ngModel)]="deadline" #deadline="ngMo ...

How do I connect with the global error handling in Vue?

Within my Vue2 application, I am seeking a method to capture global Vue errors and transmit them to a logging or monitoring service such as Sentry. After attempting to overwrite the global error handler of Vue, I noticed that console logs were no longer a ...

Currently, I'm harnessing the power of TypeScript and React to identify and capture a click event on a dynamically generated element within my document

Is there a way to detect a click on the <p> tag with the ID of "rightDisplayBtn"? I've tried using an onclick function and event listener, but neither seem to be working as expected. function addDetails() { hideModal(); addBook ...

Group records in MongoDB by either (id1, id2) or (id2, id1)

Creating a messaging system with MongoDB, I have designed the message schema as follows: Message Schema: { senderId: ObjectId, receiverId: ObjectId createdAt: Date } My goal is to showcase all message exchanges between a user and other users ...

Developing modules with Typescript

I am eager to develop custom modules for our library so that we can simply call import {Api, Map} from "ourlibrary" At the moment, I am using the following setup. import {Api} from "../../Library/Api"; import {MapPage} from "../map/map"; Could someone g ...

Encountering an issue while attempting to incorporate the confirmation email feature into a group setup, where an error is thrown indicating that only 1-2 arguments were anticipated

Issue An error message "Expected 1-2 arguments but got 3. ts(2554)" is displayed when attempting to add a confirm email as the third argument. I am currently working on an Angular 7 project where I am creating a register users form. The problem arises w ...

I'm stumped when it comes to removing values in Angular7

I am currently utilizing Angular7 in conjunction with the Loopback API to manage data. I am seeking assistance on how to implement a delete functionality within tables. Could you please offer some guidance? Despite my attempts, the code I have implemented ...

Is it possible to modify the year in the bsDatepicker to a different value?

Currently in my TypeScript code, I am importing the { BsDatepickerModule } from 'ngx-bootstrap/datepicker'; Here is the HTML code snippet I have: <div class="col-xs-12 col-12 col-md-4 form-group"> <input type="text" placehold ...

Encountering a syntax issue with pipeable operators in Angular Rxjs

I am currently in the process of rewriting this code snippet: Observable .merge(this.searchQuery$, this.lazyQuery$) .do(() => this.loadingPage()) .map(filter => this.buildURL("jaume", Config.security['appName'], filter)) .s ...

Deactivate multiple textareas within a loop by utilizing JQuery/Typescript and KnockoutJS

I am working on a for loop that generates a series of textareas with unique ids using KO data-binding, but they all share the same name. My goal is to utilize Jquery to determine if all the textareas in the list are empty. If they are, I want to disable al ...

Is it possible to use Typescript to store and access static global variables based on a unique key

I want to store variables in a static global file, like this: declare const MYVAR = 'Some unchanging data'; Later on, I would like to be able to retrieve the information using just the key 'MYVAR', for example: globalFile.findValue ...

Showing upcoming dates in an ion-datetime field within an Ionic app

I'm encountering an issue while setting up an ion-datetime input field in my Ionic 4 application. The problem I'm facing is that only the current and past dates are visible, whereas I need to display future dates as well for a "To Do" form. How c ...

Guide to integrating dexie with typescript and requirejs

My current project in Typescript involves using requirejs to load jQuery successfully. However, I'm encountering difficulties setting up Dexie. Here is how my require config is set up: require.config({ baseUrl: '', paths: { ...

Exploring i18nNext integration with antd table in React

Presently, this is the UI https://i.stack.imgur.com/CMvle.png App.tsx import "./styles.css"; import MyTable from "./MyTable"; export default function App() { const data = [ { key: "1", date: "2022-01- ...

Error message received when making an API call in React Native for Android and saving the response to a local database: 'Error: Network

Despite using axios and promises to make a call to a local database API, I am facing difficulties reaching the endpoint as I constantly receive a 'Error: Network Error' feedback in the console without any further explanation on the root cause of ...

`Connecting to Azure SQL database from multiple TypeScript API endpoints in Azure Functions`

Currently, I am developing an API in Azure Functions using TypeScript. The API consists of multiple endpoints that connect to the same Azure SQL Server. Each endpoint is set up using the HttpTrigger TypeScript template of the Azure Functions extension for ...

Enhancing RxJS arrays of Observables with supplementary data for preservation

Question: Processing Array of Observables with Metadata in Angular How can I process an array of Observables, such as using forkJoin, while passing additional metadata for each Observable to be used in the pipe and map functions? const source = {animal: & ...

problem with mat-progress-bar, BehaviorSubject is malfunctioning

I can't seem to identify the issue :( The concern lies in the fact that isLoadingLogin is consistently set to false, preventing the mat progress bar from being shown. My implementation of LoginFormComponent appears as follows: template: ` {{(isL ...