Is there, or could there be added, an equivalent of $PropertyType that works on Arrays?
In other words, $ArrayElement<Array<T>> == T
I鈥檓 working with auto-generated Flow types from GraphQL queries (using apollo-codegen), so being able to define my own types in relation to parts of those auto-generated ones is valuable:
// auto-generated
type ServicesLoadQuery = {
services: Array<{
code: string,
name: string,
hasMetadata: boolean,
}>,
};
// my type
export type Service = $ArrayElement<$PropertyType<ServicesLoadQuery, 'services'>>;
Forgive me if I鈥檝e missed this already being available.
Not sure if it's the simplest solution, but should work:
js
type _ArrayElement<El, Arr: Array<El>> = El;
type ArrayElement<Arr> = _ArrayElement<*, Arr>;
;
Awesome! That seems to work.
Great! Should it be closed then? :)
Sure. Might be nice to have it built-in, but rolling my own is not a problem.
@finneganh Could you tell me how you use it? I tried like this (and many others), but it didn't work:
type Services = ArrayElement<$PropertyType<ServicesLoadQuery, 'services'>>;
const myServices: Services = [{code:'2', name:'2', hasMetadata: true}]
$ArrayElement gives you what鈥檚 inside the array. So my guess is what you鈥檇 want is:
type Service = $ArrayElement<$PropertyType<ServicesLoadQuery, 'services'>>;
const myServices: Service[] = [{code:'2', name:'2', hasMetadata: true}]
A native flow solution for this could be nice. But thanks for providing a workaround!
@pvolok thanks so much! How did you come up with this solution? It clearly shows that there are some part of Flow I don't understand... can you explain how it actually works?
Thanks!
Thanks for providing this workaround. It would be really nice to have it as a utility type.
Most helpful comment
$ArrayElementgives you what鈥檚 inside the array. So my guess is what you鈥檇 want is: