简体   繁体   English

将类型的可能值限制为来自枚举的值

[英]Restrict the possible values of a type to a value from an enum

This is the enum:这是枚举:

enum PossibleValues {
  A = 'A',
  B = 'B',
  C = 'C'
}

And this is the type that uses the enum for one of the fields:这是将枚举用于其中一个字段的类型:

export interface MyInterface {
  name: string;
  age: number;
  value: PossibleValues;
}

I was assuming that in this case, for value it should only accept the values from enum (A, B or C) but I can put there other values and it works fine.我假设在这种情况下,对于value ,它应该只接受来自枚举(A、B 或 C)的值,但我可以将其他值放在那里并且它工作正常。

Is there a way to restrict the possible values to the ones from enum?有没有办法将可能的值限制为枚举中的值?

You can do this by extracting the type of PossibleValues and then get all keys for that type like this:您可以通过提取 PossibleValues 的类型来做到这一点,然后获取该类型的所有键,如下所示:

export interface MyInterface {
    name: string;
    age: number;
    value: keyof typeof PossibleValues;
}

Now value will only have 3 possible values A , B & C现在值将只有 3 个可能的值ABC

I've found another way to do it, it looks nice if there aren't too many possible values:我找到了另一种方法,如果没有太多可能的值,它看起来不错:

export interface MyInterface {
    name: string;
    age: number;
    value:
      | PossibleValues.A
      | PossibleValues.B
      | PossibleValues.C
}

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

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