Introducing Flow Indexed Access Types
Flow’s Indexed Access Types are a new type annotation syntax that allows you to get the type of a property from an object, array, or tuple type. They are a replacement for the $PropertyType
and $ElementType
type utilities. Not only are Indexed Access Types much more readable, but they also support autocompleting property names! Example:
type Diff = {
title: string,
};
type Title = Diff['title']; // type Title = string
const title: Title = 'Adopt Indexed Access Types';
If you’re familiar with $PropertyType
and $ElementType
, here’s a quick conversion guide:
$PropertyType<Obj, 'prop'>
→Obj['prop']
$ElementType<Obj, T>
→Obj[T]
$ElementType<$PropertyType<Obj, 'prop'>, T>
→Obj['prop'][T]
$ElementType
and $PropertyType
are now deprecated and will be removed in a future version of Flow.
Optional Indexed Access Types
Optional Indexed Access Types work like optional chaining. They allow you to access properties from nullable object types. If before you did:
type T = $ElementType<$NonMaybeType<Obj>, 'prop'> | void;
You can now do:
type T = Obj?.['prop'];
Example:
type TasksContent = ?{
tasks?: Array<{
metadata: {
title: string,
completed: boolean,
},
}>,
};type TaskData = TasksContent?.['tasks']?.[number]['metadata'];
Like optional chaining, the resulting type of an Optional Indexed Access Type includes void
. You can wrap your Optional Indexed Access Type with a $NonMaybeType<...>
if you don’t want void
in your resulting type.
Enable Indexed Access Types in your project
To support the Indexed Access Types syntax, update your dependencies:
flow
andflow-parser
: 0.155prettier
: 2.3.2babel
: 7.14
We also have an ESLint rule with auto-fixer, you can read the docs for more on how to use it.
Docs
Read the documentation for more on Indexed Access Types.