facebook / facebook/flow

Variables or 'generics' in literal types

Open
#6,226 0 comments 2 reactions 0 assignees View on GitHub
feature request
Dominant language
Rust
Stars
22.3k
Forks
1.9k
PR merge metrics
No merged PRs in 30d

Description

When I am typing redux actions for requests I currently do something like the following:

```
type Actions =
| { type: 'DO_STUFF' }
| { type: 'DO_STUFF_PENDING' }
| { type: 'DO_STUFF_FULFILLED', payload: Object }
| { type: 'DO_STUFF_REJECTED', error: Object }
| ...
```

This allows me to typecheck my reducers etc in a nice way, for instance

```
switch( action.type ) {
case DO_STUFF_FULFILLED:
return action.payload // This is fine
case DO_STUFF_REJECTED:
return action.payload.error // oops, error is on action - flow complains
...
```

However it's quite repetitive doing these type defs over and over again for each request action 'type'. After all, all _PENDING, _FULFILLED and _REJECTED actions share the same structure.

What I'd like to be able to do is something like this (imagined syntax):

```
type RequestAction =
| { type: `${T}` }
| { type: `${T}_PENDING` }
| { type: `${T}_FULFILLED`, payload: Object }
| { type: `${T}_REJECTED`, error: Object }

type Actions =
| RequestAction<'DO_STUFF'> // all that boilerplate is gone, and reused
| RequestAction<'DO_OTHER_STUFF'> // I just defined the base type once in a literal here
| RequestAction<'DO_YET_MORE_STUFF'> // and all the request actions have the same structure
```

Is this possible in flow? Sort of like generics but with a variable for a literal type? I don't think it is based on a lot of searching.

Is this a feature that could make sense or be added in future? Or is there an existing different pattern that would allow me to achieve this?

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.