I'm trying to restrict the possible values of a string based on the keys of an interface. This might not be the best way to, if you know of a better way please let me know.
interface Events {
"home": {
"button": "press"
},
"contact": {
"button": "press",
"button2": "press" | "longpress",
}
}
type EventName<
E = Events,
Context extends Extract<keyof E, string> = Extract<keyof E, string>,
Object extends Extract<keyof E[Context], string> = Extract<keyof E[Context], string>,
Action extends string & E[Context][Object] = E[Context][Object],
> = `${Context}-${Object}-${Action}`
const works: EventName = "home-button-press";
const doesnt: EventName = "home-button2-longpress";
// ^^^^^^ Error: Type '"home-button2-longpress"' is not assignable to type '"home-button-press" | "contact-button-press"'.
Is seems to only be allowing the intersection of the set of strings in both objects, where as I want to restrict the possible values based on the previous key.
"home-button2-longpress" supposed to work? Becausebutton2` does does exist in thehomeentry.