I write a function with Flow which takes a value
of MyType
and it uses only the field foo: number
:
const a = (value: MyType) => {
return value.foo;
};
However, I want to make MyType
work with any type which will have foo: number
field, e.g. with such types:
type A = {
foo: number,
baz: string,
};
type B = {
foo: number,
bar: number,
};
How can I define MyType
, so it would work with A
and B
, but also with any other type which has foo: number
?
I tried to do it with $Shape<{ foo: number }>
, but it doesn't help, because when I provide value: B
Flow starts to throw an error. Also I tried to do that as A | B
, but I got the same error and anyway it doesn't cover other cases except A
and B
. Also I thought about generic types, but it doesn't look like they can help here.
From what I read in the official documentation, you can specify that the parameter you are looking for needs a specific field of a specific type:
const a = (value: { foo: number }) => {
return value.foo;
};
This will accept any type (A, B, or any) that has at least the field "foo" defined (of type number).
However, if you only want your function to take a type A or B as parameter, you can use the following:
const a = (value: A | B) => {
return value.foo;
};