Reputation: 5171
I have this enum:
enum Options {
Option1 = "xyz",
Option2 = "abc"
}
I want to use the values for type checking by creating a union type of 'xyz' | 'abc'. Here is my attempt, but I get this 'const' assertion error:
const validValues = Object.values(Options);
const validKeys = validValues as const;
~~~~~~~~~~~ A 'const' assertion can only be applied to references to
enum members, or string, number, boolean, array, or object
literals.
What is the proper way to do this?
Upvotes: 3
Views: 4901
Reputation: 44407
You can use the Options
enum as a type
enum Options {
Option1 = "xyz",
Option2 = "abc"
}
let validValue: Options
validValue = Options.Option1
console.log(validValue) // xyz
// however, note that this is not allowed
// validValue = 'xyz'
This is another variation, not actually using enums
type Options2 = {
Option1: 'xyz',
Option2: 'abc'
}
type keys = keyof Options2 // 'Option1' or 'Option2'
type values = Options2[keys] // 'xyz' or 'abc'
let validValue2: values
validValue2 = 'xyz'
console.log(validValue2) // xyz (duh!)
// this is not allowed
// validValue2 = 'nope'
Upvotes: 1