简体   繁体   中英

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.

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:

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

Now value will only have 3 possible values A , B & C

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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