How can I write a generic type which can be used for all const assertions to enforce their respective values?
Code
const GENDER = {
male: 'm',
female: 'f',
} as const;
type GenderType = typeof GENDER[keyof typeof GENDER];
// enforces userGender to be either 'm' of 'f'
let userGender: GenderType;
userGender = 'f'; // valid
userGender = 'm'; // valid
userGender = 'o'; // invalid
How can I generalise it such that it can be used with all const assertions?
// generalise the boilerplate of
// typeof SOMETHING[keyof typeof SOMETHING]
type GenderType = ValueType<GENDER>;
type FooType = ValueType<FOO>;
type BarType = ValueType<BAR>;
type BazType = ValueType<BAZ>;
ValueType<typeof FOO>but noValueType<FOO>, becauseFOOis a value but generics take types and not values.type ValueType<T> = T[keyof T]and thenValueType<typeof GENDER>is okay, great. If you insist onValueType<GENDER>then the answer here is just "no, this can't be done" and I can write up an explanation for why. Let me know which way to go with this.