patrick
patrick

Reputation: 9722

how can I restrict the keys of an object to be the values of an object?

I have an object defined with string keys and number values:

class MyService {
  private static readonly MAPPING: { [ index: string ]: number } = {
    a: 16,
    b: 32,
  };
}

And I would like to have another object that only allows the values (numbers) defined in that mapping as keys



class MyService {
  private static readonly MAPPING: { [ index: string ]: number } = {
    a: 16,
    b: 32,
  } as const;
  public static states: { [ index in ?!? (Object.values(MyService.MAPPING)) ?!? ]: boolean } = {}; // <-- clearly this is wrong
}

So that: MyService.states[16] = true would be valid, but MyService.states[17] = true would not.

How can I accomplish this?

Upvotes: 0

Views: 1040

Answers (1)

Andrietta
Andrietta

Reputation: 36

Since you are not allowed to define a type within a class, you will have to define the type using the constant object on the root level of the file and use it in your class.

const MAPPING = {
  a: 16,
  b: 32,
} as const;

type MAPPING_VALUE = typeof MAPPING[keyof typeof MAPPING];

class MyService {
  public static readonly MAPPING: { [index: string]: number } = MAPPING;
  public static states: {
    [index in MAPPING_VALUE]: boolean;
  } = {
    16: true,
    32: false,
  };
}

Upvotes: 1

Related Questions