Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript 'const' assertion on string enum values

Tags:

typescript

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?

like image 576
techguy2000 Avatar asked Feb 12 '26 17:02

techguy2000


1 Answers

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'
like image 179
Klas Mellbourn Avatar answered Feb 14 '26 14:02

Klas Mellbourn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!