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
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
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.
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]];
To convert to a string before casting it to the specified enum, use the following code snippet:
const variable = key as string as EnumValue
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
.
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
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 ...
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" }, ...
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. [ { ...
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 ...
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 ...
The code snippet originally utilized - import { Create } from '@material-ui/icons'; <DroppableFolder count={draftsCount} sidebarOpen={open} folderId={FolderType.Drafts} Icon={Create} name="Dr ...
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 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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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" ...
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 ...
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 ...
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(); } ...
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 ...
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 ...