Replace the type of an object property in a Flow type

flowtype, javascript

Solution

I can think of two solutions:

1) a parametric type alias

type Parametric<T> = {
  foo: T,
  bar: number,
  // ... many other properties
};

type A = Parametric<string>;
type B = Parametric<?string>;

2) intersections

type Base = {
  bar: number,
  // ... many other properties
};

type A = Base & { foo: string };
type B = Base & { foo: ?string };

Problem

Let's say we have defined a very simple object type: ``` type A = { foo: string, bar: number, // ... many other properties }; ``` Now we'd like to define a variant of this type, just replacing the type of `foo` by `?string`: ``` type A2 = { foo: ?string, bar: number, // ... many other properties, with the same types as in A }; ``` How can that be done, without having to define the whole type again? It'd be enough if the answer only worked in the particular case of replacing property type `T` by `?T`, since that is my most frequent problem.

Original source