Here is a type definition that allows for specific responses:
type Response = 'n_a' | 'n_o' | 'yes' | 'no'
I want to create a type that ensures underscores are replaced with slashes:
type ReplaceUnderscoreWithSlash<T extends string> =
T extends `${infer Head}_${infer Tail}` ? `${Head}/${Tail}` : T;
This works as intended:
type HumanReadableResponses = ReplaceUnderscoreWithSlash<Response>;
Now, I need to make a lookup object for runtime conversion, enforcing type safety:
I tried this but it doesn't provide the desired key -> value type safety:
type LookupObject<T extends string> = Record<T, ReplaceUnderscoreWithSlash<T>>;
For example:
const lookupObject: LookupObject<Response> = {
n_a: 'n/a',
n_o: 'n/a', // This should throw an error because only 'n/o' is valid
no: 'no',
yes: 'yes',
};
Is it possible to achieve what I'm trying to do here?