Dynamic property names in flow typed object

Sam Matthews picture Sam Matthews · Feb 11, 2017 · Viewed 7.9k times · Source

I'm slowly and surely working flowType into my code, but I'm struggling with one concept.

How do I specify the type of unknown, dynamically named properties of an object?

For example my user object might have an object containing organisations with unique keys.

How would I define this?

export type User = ?{
  currentOrg: string,
  displayName?: string,
  email: string,
  emailVerified: boolean,
  newAccount: boolean,
  organisations?: {
     UNKNOWNKEY?: string {
       orgData1: string,
       orgData2: string,
     }
  },
  uid: string,
  photoUrl?: string,
};

Would really appreciate any help on this. Thanks!

Answer

Peter Hall picture Peter Hall · Feb 12, 2017

Flow has specific syntax for objects that behave like maps:

{ [key: K]: V }

where K is they type of the keys and V is the type of the values.

Your full example would look like:

export type User = {
  currentOrg: string,
  displayName?: string,
  email: string,
  emailVerified: boolean,
  newAccount: boolean,
  organisations?: { [key: string]: string },
  uid: string,
  photoUrl?: string,
};