简体   繁体   English

对字符串枚举值的打字稿“const”断言

[英]Typescript 'const' assertion on string enum values

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' |我想通过创建'xyz'的联合类型来使用类型检查的值 | 'abc'. 'ABC'。 Here is my attempt, but I get this 'const' assertion error:这是我的尝试,但我收到此“const”断言错误:

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?这样做的正确方法是什么?

You can use the Options enum as a type您可以使用Options枚举作为类型

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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM