Paulius Liekis
Paulius Liekis

Reputation: 1730

What's the equivalent of Typescript's "key in EnumType" in Flowtype?

Typescript allows me to write such code:

export enum ActivityType {
  FREERIDE = "FREERIDE",
  SKI_TOUR = "SKI_TOUR",
}

const activityDesctription: {
  [key in ActivityType]: string
} = {
  [ActivityType.FREERIDE]: "Freeriding",
  [ActivityType.SKI_TOUR]: "Ski-touring"
};

The in expression gives me very strict type-safety, i.e. activityDesctription has to contain definitions for each member of enum, not less, not more. It also generates appropriate index operators.

How do I do in expression in Flowtype?

Upvotes: 0

Views: 87

Answers (1)

Andrew Smith
Andrew Smith

Reputation: 1444

Updated answer

If you want activityDescription to be exactly the same keys as ActivityType and to complain when you're missing some, use $ObjMap (docs). Flow try

const ActivityType = {
  FREERIDE: "FREERIDE",
  SKI_TOUR: "SKI_TOUR",
}

type StringValue = <V>(V) => string
const activityDescription: $ObjMap<typeof ActivityType, StringValue> = {
  [ActivityType.FREERIDE]: 'yo',
  [ActivityType.SKI_TOUR]: 'this is fun',
}

Old answer

You can use $Keys<typeof obj> which will extract the keys of the obj. Docs, and Flow try.

UPDATE: As noted in the comments, this solution does not throw compile errors when keys of ActivityType are missing from activityDescription.

const ActivityType = {
  FREERIDE: "FREERIDE",
  SKI_TOUR: "SKI_TOUR",
}

const activityDescription: {
  [$Keys<typeof ActivityType>]: string
} = {
  [ActivityType.FREERIDE]: "Freeriding",
  [ActivityType.SKI_TOUR]: "Ski-touring",
  error: 'error' // flow errors here
};

Upvotes: 1

Related Questions