Closed
Description
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"
Metadata
Metadata
Assignees
Type
Projects
Milestone
Relationships
Development
No branches or pull requests
Activity
jgbpercy commentedon Sep 22, 2020
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:
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 commentedon Sep 22, 2020
Unclear if this is a bug report or a question; see #26362