Skip to content
Advertisement

How to create new Flow type having all properties of existing type but optional

I have a type State in which all fields are required:

type State = {
  title: string,
  items: [],
  isActive: boolean,
};

I need to create a new type with all properties the same as in State but not required:

type StateUpdater = {
  title?: string,
  items?: [],
  isActive?: boolean,
};

// ({title: 'hello'}: State) — INVALID
// ({title: 'hello'}: StateUpdater) — OK

How can I implement this similarly to the following Flow pseudocode?

type StateUpdater = State.mapKeyValue(() => typeKey?: typeValue)

Advertisement

Answer

You can use $Shape utility:

type State = {
  title: string,
  items: [],
  isActive: boolean,
};

type StateUpdater = $Shape<State>;

$Shape Copies the shape of the type supplied, but marks every field optional.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement