What are best practices for optional parameters?
See original GitHub issueConsider 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 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
Issue Analytics
- State:
- Created 6 years ago
- Comments:6 (3 by maintainers)
Top GitHub Comments
@GAntoine great idea, however part of my question relates to whether the flow-typed definitions for raven.js should be changed. But thank you, I’ll post the question there
@GAntoine - Thank you. When i get an answer on any channel I’ve posted on, I’ll be sure to report back here and close myself.