Converting and Casting Enums in TypeScript

Is there a way to convert one enum into another when they have the same values?

enum Enum1 {
  Value = 'example'
}

enum Enum2 {
  Value = 'example'
}

const value = Enum1.Value
const value2 = value as Enum2

Answer №1

Presented here is a solution catered towards number values. However, it's worth noting that this method can be considered "risky" since there is no validation or confirmation of the conversion process, thus failing to meet your expectations for compile-time checks. Essentially, you must first cast to an intermediate compatible type (such as number, string, any, or unknown) before casting to the second enum. This approach essentially removes any significant semantic checking from the equation. By casting, you inherently sacrifice compile-time checking.

enum SeverityLevel {
    Verbose = 0,
    Warning = 1
}

enum InternalSeverity {
    Verbose = 0,
    Warning = 1
}


function CallMe(severity: SeverityLevel) {
    console.log(`SeverityLevel: ${severity}`);
}

function Convert(severity: InternalSeverity) {
    console.log(severity);
    console.log(SeverityLevel[severity]);
    console.log(InternalSeverity[severity]);

    CallMe(severity as number as SeverityLevel);
}

Convert(InternalSeverity.Warning);

An alternative approach could involve creating a comprehensive conversion function that explicitly maps values and ensures consistency between enums. For instance:

switch (severity) {
   case SeverityLevel.Warning:
      return InternalSeverity.Warning;
      break;

This method facilitates seamless conversion between enums, adapts well to changes in underlying values, assuming the enum's purpose is to represent values via names rather than the actual values themselves, and upholds compile-time integrity checks (in the event of key removal from the enum). If prioritizing the actual values over their names, a slight adjustment in strategy might be necessary.

Answer №2

If numbers are used instead of strings for the enum values, this code snippet will function correctly:

enum Enum1 {
  Key1 = 2
}

enum Enum2 {
  Key1 = 2
}

const key = Enum1.Key1
const key2 = Enum2[Enum1[key]];

Answer №3

To convert to a string before casting it to the specified enum, use the following code snippet:

const variable = key as string as EnumValue

Answer №4

It appears that Typescript doesn't bother to validate the potential values, which causes it to overlook the compatibility of these enums. What I'm currently attempting is

const key2 = key as Enum1 & Enum2

While not ideal since it doesn't strictly enforce enum compatibility, it's still a better option than casting to string or any.

Answer №5

When the program is running, the variable will hold the enum value (key in this scenario). Therefore, you can easily cast it using any and it will function correctly.

const key = Enum1.Key1
const key2: Enum2 = key as any

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

Navigating an Array in Typescript

Angular is linked to node.js, which interacts with mongodb to fetch data successfully. However, I am now faced with the challenge of mapping variables in my typescript component to the backend node.js. When viewing the data structure in the browser consol ...

Determine the data type of a property by referencing the data type of another property within an array of objects using TypeScript

I am working with a specific type of interface called Route that consists of name and path properties. interface Route { name: string, path: string } const routes = [ { name: "first", path: "/first" }, ...

Filtering arrays of objects dynamically using Typescript

I am looking to create a dynamic filter for an array of objects where I can search every key's value without specifying the key itself. The goal is to return the matched objects, similar to how the angular material table filters all columns. [ { ...

Unused code splitting chunk in React production build would improve performance and efficiency of

When running the command npm run build, a build directory is generated with js chunks. I have observed an unfamiliar file named [number].[hash].chunk.js that does not appear in the list of entrypoints in the asset-manifest.json file. Instead, this mysteri ...

Challenges arise when integrating Angular with Firebase, particularly in the realms of authentication and user

Currently, I am working on a project using Angular and Firebase. However, in the auth.service.ts file, Visual Studio Code is not recognizing the imports for auth and User. import { auth } from 'firebase/app'; import { User } from 'fireba ...

Troubleshooting Typescript Compilation Error in React - Cannot assign type 'Element' to type 'FunctionComponent<{}>'

The code snippet originally utilized - import { Create } from '@material-ui/icons'; <DroppableFolder count={draftsCount} sidebarOpen={open} folderId={FolderType.Drafts} Icon={Create} name="Dr ...

Remove the user along with all of their associated documents from Firestore

When a user wants to delete their account, I need to ensure that the 'documents' they created in Firebase are deleted as well. After some research online, I came across the following code snippet: deleteAccount() { const qry: firebase. ...

Is there a way to retrieve a compilation of custom directives that have been implemented on the Vue 3 component?

Is there a way to retrieve the list of custom directives applied to a component? When using the getCurrentInstance method, the directives property is null for the current component. I was expecting to see 'highlight' listed. How can I access the ...

What is the best way to determine if a user is currently in a voice channel using discord.js?

Is there a way for me to determine if a user is currently linked to a voice channel? I am trying to implement a command that allows me to remove a user from a voice channel, and here is how I am attempting to check: const user: any = interaction.options.ge ...

The declared type 'never[]' cannot be assigned to type 'never'. This issue is identified as TS2322 when attempting to pass the value of ContextProvider using the createContext Hook

I'm encountering an issue trying to assign the state and setState to the value parameter of ContextProvider Here's the code snippet:- import React, { useState, createContext } from 'react'; import { makeStyles } from '@material-ui ...

Utilize the optional chaining feature when accessing properties that may be optional

I recently encountered an issue in my Typescript project where accessing properties or functions of optional properties did not throw any errors. Here is an example: type Example = { bar?: string[] } const foo: Example = {} // Although no error occu ...

TypeScript implementation of a reusable component for useFieldArray in React Hook Form

I'm currently working on a dynamic form component using react-hook-form's useFieldArray hook and facing issues with setting the correct type for field. In order to configure the form, I have defined a type and default values: export type NamesAr ...

Is it Feasible to Use Component Interface in Angular 5/6?

My main goal is to create a component that can wrap around MatStepper and accept 2..n steps, each with their own components. In other languages, I would typically create an interface with common behavior, implement it in different components, and then use ...

Create dynamic breadcrumb trails using router paths

I am currently working on developing a streamlined breadcrumbs path for my application. My goal is to achieve this with the least amount of code possible. To accomplish this, I have implemented a method of listening to router events and extracting data fr ...

Typescript does not process and compile files located within a specified directory

Recently, I embarked on a small TypeScript project and took the time to create the tsconfig.json configuration file. { "compilerOptions": { "target": "es5", "module": "commonjs", "sourceMap": true }, "files": [ "./typings/index.d.ts" ...

Implementing Global Value Assignment Post Angular Service Subscription

Is there a way to globally assign a value outside of a method within my app component? This is how my service is structured: import { NumberInput } from '@angular/cdk/coercion'; import { HttpClient } from '@angular/common/http'; import ...

The TypeScript factory class anticipates an intersection

In my code, I have a class factory called pickSomething that generates a specific type based on a key provided from a ClassMap: class A { keya = "a" as const; } class B { keyb = "b" as const; } type ClassMap = { a: A b: B } c ...

What exactly is the data type of setInterval in TypeScript?

If I want to define the type of a variable that will be used with setInterval in the following code snippet: this.autoSaveInterval = setInterval(function(){ if(this.car.id){ this.save(); } else{ this.create(); } ...

Associate keys with strings and then map them to a specific type of strings in Typescript

I am endeavoring to develop a React component that extends the Octicons icon library available from Github at @githubprimer/octicons-react. One of the components exported by the library is the iconsByName type, which has the following structure: type ico ...

Tips for uploading images, like photos, to an iOS application using Appium

I am a beginner in the world of appium automation. Currently, I am attempting to automate an iOS native app using the following stack: appium-webdriverio-javascript-jasmine. Here is some information about my environment: Appium Desktop APP version (or ...