Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

The values of the traversable enum generate the union type #40691

Closed
victorykong opened this issue Sep 22, 2020 · 2 comments
Closed

The values of the traversable enum generate the union type #40691

victorykong opened this issue Sep 22, 2020 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@victorykong
Copy link

victorykong commented Sep 22, 2020

Search Terms

enum
keyof
typeof

Use Cases

type num = VALUE.ZERO | VALUE.ONE | VALUE.TWO;
const number0: num = 0;
const number1: num = 1;
const number2: num = 2;
const number3: num = 3; // Success??

Examples

How do I define a type constraint in my enumeration value?

enum VALUE {
  ZERO,
  ONE,
  TWO,
}
type KEY = keyof typeof VALUE; // "ZERO" | "ONE" | "TWO"
@jgbpercy
Copy link

Sadly the enum feature in TS doesn't achieve what you want here, assuming I'm understanding what you're asking. You can do something like this:

export const VALUE = {
    ZERO: 0,
    ONE: 1,
    TWO: 2
} as const;

type ValueType = typeof VALUE;

type Value = ValueType[keyof ValueType];

const One: Value = 1; // Ok

const Three: Value = 3; // Error

The flaw with the above is that nothing stops you from using values from other "enums" as the type Value (if their numerical value is 0, 1 or 2). For that, you would need some version of branded types.

Btw if your enum values don't come from some external source that forces them to be integers, string literal unions are often a better idea for reasons like the above.

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Sep 22, 2020
@RyanCavanaugh
Copy link
Member

Unclear if this is a bug report or a question; see #26362

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

3 participants