Utilize string variables within TypeScript's enumeration feature

Can string variables be used in enums in TypeScript? Strings can be used in enum like so:

enum AllDirections {
  TOP = 'top',
  BOTTOM = 'bottom',
  LEFT = 'left',
  RIGHT = 'right',
}

However, trying to use variables with strings like this:

const top: string = 'top'
const bottom: string = 'bottom'
const left: string = 'left'
const right: string = 'right'

enum AllDirections {
  TOP = top,
  BOTTOM = bottom,
  LEFT = left,
  RIGHT = right,
}

leads to the following error message:

Type 'string' is not assignable to type 'AllDirections'

Answer №1

If you're keen on pursuing this approach, one option is to define the values as any:

enum AllDirections {
  TOP = top as any,
  BOTTOM = bottom as any,
  LEFT = left as any,
  RIGHT = right as any
}

An issue with this method arises if you are assigning these values as strings, necessitating an additional assertion to convert them to string type. Not an ideal situation:

let str: string = AllDirections.TOP as any as string;

Alternatively, while a bit more verbose, you can ensure that the members have the correct type by utilizing an object:

// exclude explicit string types for proper typing of 
// string literal values
const top = 'top';
const bottom = 'bottom';
const left = 'left';
const right = 'right';

type AllDirections = Readonly<{
    TOP: typeof top,
    BOTTOM: typeof bottom,
    LEFT: typeof left,
    RIGHT: typeof right
}>; 

const AllDirections: AllDirections = {
    TOP: top,
    BOTTOM: bottom,
    LEFT: left,
    RIGHT: right
};

Another approach would be flipping where the string values are stored:

 enum AllDirections {
    TOP = 'top',
    BOTTOM = 'bottom',
    LEFT = 'left',
    RIGHT = 'right',
}

const top = AllDirections.TOP;
const bottom = AllDirections.BOTTOM;
const left = AllDirections.LEFT;
const right = AllDirections.RIGHT;

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

Provide an immutable parameter to a function that will not cause any changes

Looking to develop a function named batchUsers, requiring a parameter of type readonly string in order to create a DataLoader. However, when calling the User.findBy function within my batchUsers function, it's causing issues due to conflicting paramet ...

The Context API's `useContext` hook appears to be malfunctioning, persistently

My situation is as follows: export const LocationContext = createContext(null); export const LocationProvider = LocationContext.Provider; export const useLocationContext = () => useContext(LocationContext); Using the Provider: export const Search = () ...

Encounter a Typescript error when dealing with "app.ws" while using express-ws

I have a small project in mind where I want to create a BabyCam that can be accessed from any web browser using a Raspberry Pi Zero. My plan is to set up a web socket using express-is to stream video to multiple clients. I'm utilizing the raspivid-str ...

The routing navigate method is failing to direct to the desired component

For the past day, I have been struggling to find a solution to my issue but without success. The routing seems to be malfunctioning as it keeps showing the HTML content from app.component.html even when I try changing the path in the URL. Here is a snippe ...

In the latest version of Expo SDK 37, the update to [email protected] has caused a malfunction in the onShouldStartLoadWithRequest feature when handling unknown deeplinks

After updating to Expo SDK 37, my original code that was previously functioning started encountering issues with <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0e7c6b6f6d7a23606f7a67786b23796b6c78667f79627a">[email prot ...

IE11 and how it handles Typescript and promises

Currently, I am utilizing Typescript version 2.4.2 along with Webpack for compilation purposes. Despite successful compilation, when running my code on IE11, an error 'Promise' is undefined arises. Below is a glimpse of my tsconfig: { "comp ...

TypeScript integrated Cypress code coverage plugin

I've been attempting to integrate the @cypress/code-coverage plugin with TypeScript in my project, but so far I haven't had any success. Here is a breakdown of the steps I've taken thus far: Followed all the instructions outlined in https:/ ...

Angular StrictNullChecks: "Error - object may be null"

I am encountering an issue with the 'strictNullChecks' setting in my Angular project. This has resulted in numerous errors across my templates (.html), such as: <input #inputValue type="text" (keyup.ent ...

How can we reduce the size of a JSON object in Typescript before sending it to the client?

Currently, I am faced with a common challenge. I have a database object that is a standard JS object originating from a document database, and my goal is to transmit this object to the client. However, certain fields contain sensitive information that shou ...

Employing square bracket notation based on the input data

I'm currently in the process of enhancing some code within my library, but I've encountered a perplexing issue with bracket notation not functioning as expected when attempting to call an imported class. The parameter type expects a camelCased s ...

What is the process for comparing two objects in TypeScript?

There is a unique class named tax. export class tax { private _id: string; private _name: string; private _percentage: number; constructor(id: string = "", taxName: string = "", percentage: number = 0) { thi ...

ESLint and Prettier are butting heads when trying to run their commands consecutively

My package.json file includes two commands: "format": "prettier --write \"{src,{tests,mocks}}/**/*.{js,ts,vue}\"", "lint": "eslint . -c .eslintrc.js --rulesdir eslint-internal-rules/ --ext .ts,.js,.vue ...

Utilizing getters and setters with v-model in a class-based component: A step-by-step guide

Transitioning from an angular background to vuejs has been challenging for me as a newbie. I've encountered issues while trying to bind setter/getter in v-model for an input field. Interestingly, when I directly bind it to a variable, everything works ...

How can I store various data types in a single array in TypeScript?

I have a scenario I need help with. Let's say we have two interfaces, Cats and Dogs. How can I create an array that can store both Cats and Dogs? interface Cats { name: string; age: number; } interface Dog { owner: string; } const cat1: Cat ...

Typescript is missing Zod and tRPC types throughout all projects in the monorepo, leading to the use of 'any'

Recently, I've found myself stuck in a puzzling predicament. For the last couple of weeks, I've been trying to troubleshoot why the types are getting lost within my projects housed in a monorepo. Even though my backend exposes the necessary types ...

The quantity of documents queried does not align with the number of data counts retrieved from Firestore

Facing an issue with calculating the Firestore read count as it keeps increasing rapidly even with only around 15 user documents. The count surges by 100 with each page reload and sometimes increases on its own without any action from me. Could this be due ...

Are you harnessing the power of Ant Design's carousel next and previous pane methods with Typescript?

Currently, I have integrated Ant Design into my application as the design framework. One of the components it offers is the Carousel, which provides two methods for switching panes within the carousel. If you are interested in utilizing this feature using ...

How to extract key-value pairs from an object in a TypeScript API request

I am trying to extract the data '"Cursed Body": "100.000%"' from this API response using TypeScript in order to display it on an HTML page. Can anyone help me figure out how to do this? API Response { "tier": &q ...

Incorporate a generic type into a React Functional Component

I have developed the following component: import { FC } from "react"; export interface Option<T> { value: T; label: string; } interface TestComponentProps { name: string; options: Option<string>[]; value: string; onChang ...

Embracing Typescript promises over jQuery deferred for improved code efficiency and reliability

Currently, I have the following lines of code that utilize the JQueryDeferred object from the type definition class jquery.d.ts. My goal is to replace jQuery deferred with TypeScript promises. Here is the existing JQueryDeferred code: class A { privat ...