How to Convert a Computed Value to a Literal for Enum Initialization

How to convert a computed value to a literal for enum initialization

You can only use literals for the raw values of type-backed enums.

To get this to work, you have to calculate the raw value of the calculation you're performing and paste that literal in as an approximation:

public enum ANGLE_TYPE : Double {
case DEGREES = 0.0174532925199433
case RADIANS = 1.0
}

The only other option is to not have a type-backed enum and manually provide the rawValue property:

public enum ANGLE_TYPE {
case DEGREES, RADIANS

var rawValue: Double {
get {
switch self {
case .DEGREES:
return Double(CGFloat(M_PI / 180.0))
case .RADIANS:
return 1.0
}
}
}
}

This might make sense because this means you don't have the init(rawValue:Double) initializer, which doesn't make a whole lot of sense in this case probably.

As a side note, this all caps thing is really unnecessary. I'd much prefer something more like this:

public enum AngleMeasureUnit {
case Degrees, Radians
}

How to assign computed values to enum using typescript

that's not how enum work, you can't assign dynamic values to enum, computed values are not permitted in an enum with string valued members.

https://www.typescriptlang.org/docs/handbook/enums.html

The enum member is initialized with a constant enum expression. A constant enum expression is a subset of TypeScript expressions that can be fully evaluated at compile time. An expression is a constant enum expression if it is:

  • a literal enum expression (basically a string literal or a numeric literal)

  • a reference to previously defined constant enum member (which can originate from a different enum)

  • a parenthesized constant enum expression

  • one of the +, -, ~ unary operators applied to constant enum expression
    +, -, *, /, %, <<, >>, >>>, &, |, ^ binary operators with constant enum expressions as operands

Initialize a JavaScript/TypeScript object with computed property names from enum/array values

You can use computed properties manually:

const obj1 = { [Amenities.FreeWeights]: true, [Amenities.CardioMachines]: true };

Or use Object.values() on the enum, map the keys to [key, value] pairs, and convert to an object with Object.fromEntries() (requires lib: es2019 or later in tsconfig):

const obj2 = Object.fromEntries(Object.values(Amenities).map(k => [k, true]));

TS Playground

How to get an enum value from a string value in Java

Yes, Blah.valueOf("A") will give you Blah.A.

Note that the name must be an exact match, including case: Blah.valueOf("a") and Blah.valueOf("A ") both throw an IllegalArgumentException.

The static methods valueOf() and values() are created at compile time and do not appear in source code. They do appear in Javadoc, though; for example, Dialog.ModalityType shows both methods.

Create an enum with string values

TypeScript 2.4

Now has string enums so your code just works:

enum E {
hello = "hello",
world = "world"
};

/p>

TypeScript 1.8

Since TypeScript 1.8 you can use string literal types to provide a reliable and safe experience for named string values (which is partially what enums are used for).

type Options = "hello" | "world";
var foo: Options;
foo = "hello"; // Okay
foo = "asdf"; // Error!

More : https://www.typescriptlang.org/docs/handbook/advanced-types.html#string-literal-types

Legacy Support

Enums in TypeScript are number based.

You can use a class with static members though:

class E
{
static hello = "hello";
static world = "world";
}

You could go plain as well:

var E = {
hello: "hello",
world: "world"
}

Update:
Based on the requirement to be able to do something like var test:E = E.hello; the following satisfies this:

class E
{
// boilerplate
constructor(public value:string){
}

toString(){
return this.value;
}

// values
static hello = new E("hello");
static world = new E("world");
}

// Sample usage:
var first:E = E.hello;
var second:E = E.world;
var third:E = E.hello;

console.log("First value is: "+ first);
console.log(first===third);

Use object literal as TypeScript enum values

Update: find @Javarome's answer below, which is more elegant. I suggest using his way.

If you need to use Type, try adding some code.
usage: getPizzSizeSpec(PizzaSize.small).value

enum PizzaSize {
small,
medium,
large
}
interface PizzaSizeSpec {
key: number,
value: number
}
function getPizzaSizeSpec(pizzaSize: PizzaSize): PizzaSizeSpec {
switch (pizzaSize) {
case PizzaSize.small:
return {key:0, value: 25};
case PizzaSize.medium:
return {key:0, value: 35};
case PizzaSize.large:
return {key:0, value: 50};
}
}

How to cast a string to an Enum during instantiation of a dataclass in Python

I think __post_init__ (as you edited added to your question) is your best alternative. dataclass doesn't support the kind of value transformer you want. (For that, you might want to look at Pydantic or the attrs package.)

from dataclasses import dataclass, InitVar
from enum import Enum

class DummyAttribute(Enum):
FOO = "foo"
BAR = "bar"

@dataclass
class DummyClass:
dummy: DummyAttribute = field(init=False)
dummyStr: InitVar[str]

def __post_init__(self, dummyStr):
self.dummy = DummyAttribute(dummyStr)

Raw value for enum case must be a literal

That's because 1 << 0 isn't a literal. You can use a binary literal which is a literal and is allowed there:

enum GestureDirection:UInt {
case Up = 0b000
case Down = 0b001
case Left = 0b010
case Right = 0b100
}

Enums only support raw-value-literals which are either numeric-literal (numbers) string-literal­ (strings) or boolean-literal­ (bool) per the language grammar.

Instead as a workaround and still give a good indication of what you're doing.



Related Topics



Leave a reply



Submit