facebook / facebook/flow

What are best practices for optional parameters?

Open
#5,490 1 comment 0 reactions 0 assignees View on GitHub
Dominant language
Rust
Stars
22.3k
Forks
1.9k
PR merge metrics
No merged PRs in 30d

Description

Consider this code. It's a redux reducer, but you don't need to know redux to help me with this issue. I was trying to follow [this](https://flow.org/en/docs/react/redux/#toc-typing-redux-reducers) doc, and am running into problems.

```
// Types
// Types
type InitAction = { +type: typeof INIT | typeof INIT_SUCCESS };
type ErrorAction = { +type: typeof INIT_ERROR, +error: Error };
type Action = InitAction | ErrorAction; // flow doesn't seem to be doing

type InitState = {
+error?: Error
};

export default function InitReducer(
state: InitState = {},
{ type, error }: Action = {} // i need this param or jest complains
): InitState {
switch (type) {
case INIT_ERROR:
Raven.captureException(error, { state }); // flow complains, error doesn't always exist
return {
...state,
error
};
case INIT_SUCCESS:
case INIT:
default:
return state;
}
}
```

Raven.captureException(error, { state }); expects error to be of type Error. Whenever the case is INIT_ERROR, error will always be defined. Is there a way to imply this in flow? Originally I thought the flow-types on the actions imply this, but flow doesn't seem to like this. To fix it, I've gone with a more-generic Action type.

```
type Action = {
+type: string,
+error?: Error
};
```

however even with this Action-type i still need this line

```
error && Raven.captureException(error, { state }); // flow is now happy, but this seems wrong
```

I thought maybe flow would be smart enough to know when INIT_ERROR is the type, an error will always exist. Another way I've found to get flow to stop complaining, change Raven.captureException to allow Error | void, but this seems wrong too.

Am i doing something completely wrong? Did I find a bug? What should I do?

Apologies in advance - I'm very new to flow

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.