As I dive deeper into the TypeScript type system, I find myself grappling with an interface design query. Can anyone lend a hand?
My goal is to craft an interface in TypeScript where certain object keys are of a generic type and all other keys should be of a consistent type. Despite my attempts with conditional types and union types containing 'never', I haven't been able to crack the code on this.
type Command = () => void;
type ViewState = {[key: string]: any};
export interface ViewModel<T extends ViewState> {
viewState: T;
// The following line is what does not work
[key: Omit<string, 'viewState']: Command;
}
// Here's the desired outcome,
interface LabelState {
label: string;
}
interface LabelModel<LabelState> {
viewState: LabelState;
updateLabel: Command;
}
interface MenuState {
menuItems: string[];
}
interface MenuModel<MenuState> {
viewState: MenuState;
openMenu: Command;
closeMenu: Command;
};
I realize this may not be essential, but it would be satisfying to have all methods defined as a Command
. It seems like it should be doable. Is there someone out there who can confirm whether or not this is achievable? And if so, what am I overlooking?