I'd like to have a constant that references keys of an interface. I want this constant to be type-checked to be sure that the keys are properly named, and I also want them to be typed as literals.
If I do the following:
interface MyInterface {
keyA: string;
keyB: string;
}
export const MY_KEYS: Record<string, keyof MyInterface> = {
CONSTANT_KEY_A: 'keyA',
CONSTANT_KEY_B: 'keyB',
} as const;
MY_KEYS.CONSTANT_KEY_A
then MY_KEYS.CONSTANT_KEY_A
is of type 'keyA' | 'keyB'
. But I want it to be 'keyA'
!
If I remove Record<string, keyof MyInterface>
then it will work, but then my keys are no longer type checked to be in the keys of MyInterface.
Any idea on how I can achieve that?
I could for example add a second dead variable that does the Record check and keep my first one only with as const
and not casted as Record, but it's pretty verbose and not really clear.
Thank you!