Edit: Ok it appears that the code I posted below works flawlessly, so there's something else going on. Brb...

I am trying to specify a type from two enums or union types, but when I do I get the error

Object literal may only specify known properties, and 'x' does not exist in type 'y'

I thought maybe the problem was with using enums instead of a union type, but I haven't had any luck with that either. Also changing to interfaces and using [context in keyof uiContexts] didn't give any joy. I think there's something fundamental I'm misunderstanding here.

So I'm wanting to define inputs for various different program states.

type inputs = 'up' | 'down' | 'left' | 'right'

type uiContexts = 'mainMenu' | 'subMenu'

class Parser {
  private contexts: {[context in uiContexts]: {[i in inputs]: () => void}} = {
    mainMenu: {
      up: () => {},
      down: () => {},
      left: () => {},
      right: () => {},
    },
    subMenu: {
      up: () => {},
      down: () => {},
      left: () => {},
      right: () => {},
    },
  }
}

expected: the type definition {[context in uiContexts]: [i in inputs]: () => void} to fit the data given.

Actual: compiling error Object literal may only specify known properties, and 'subMenu' does not exist in type '{ mainMenu: { up: () => void; down: () => void; left: () => void; right: () => void; }

0 Answers