Defining an object consisting of other object types in Flow

74 Views Asked by At

I have an object that looks like this:

const myObject = {
  a: {
    id: 'abc'
  },
  b: {
    id: 'def'
  },
  c: {
    id: 'ghi'
  },
}

a, b, and c all have the same structure, so I would like to define a single type for those (abcType below), and make sure myObject consists out of these types.

So basically:

type abcType = {
  id: String
}

type myObjectType = {
  [whateverKey]: abcType
  // ^^ Dummy code, this doesn’t actually work
}

However I can’t seem to find the proper way to define this in Flow. Anybody who’s ran in to the same problem?

1

There are 1 best solutions below

0
On BEST ANSWER
type abcType = {
  id: string // lower-case 's'
}

type myObjectType = {
  [string]: abcType // 'string' type for the object keys.
};

const myObject: myObjectType = {
  a: {
    id: 'abc'
  },
  b: {
    id: 'def'
  },
  c: {
    id: 'ghi'
  },
}

should be all you need.