Home > Mobile >  Restrict the possible values of a type to a value from an enum
Restrict the possible values of a type to a value from an enum

Time:09-22

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?

CodePudding user response:

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

CodePudding user response:

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
}
  • Related