Reputation: 9722
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
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