I'm using flow-coverage-report, and it enlightened me to the fact that we can't type try/catch blocks. I've tried looking everywhere for documentation on try/catch and Flow, but couldn't find a thing.
This is a problem if I'm going to use the error to update my Redux store, for example.
This kind of typing doesn't help with coverage:
const result: MessageType | Error = (rawMessage) => {
try {
return JSON.parse(rawMessage);
} catch(e) {
return e;
}
};
Additionally, I tried to type the caught error (in most cases, I know which types of errors are possible), but this is a syntax error, unexpected token:
type ParseError = { [ error properties here ] };
try {
return JSON.parse(rawMessage);
} catch(e: ParseError) {
return e;
}
Wondering if there is a plan for adding try/catch typing for Flow, or if there are other approaches I could take. Thank you!
There is no workaround at the moment. See https://github.com/facebook/flow/pull/3259
Well you could always use type-casting.
In the long-term I can only see two ways to solve this:
throws syntax from swift.This would mean that JSON.parse would have a type that looks like this:
declare var JSON: {
parse(str: string): mixed throws ParseError;
}
This would make the code way more type-safe and force you to always check for uncaught errors. However, this would also push developers into relying on throwing exceptions.
My recommendation would be to...
This would mean that other than in built-in function, your code should avoid ever throwing anything. Instead you functions should return union types of Value | Error.
This is a much better approach as you get the same type safety benefits without sacrificing performance by using try-catch.
That is great news - looking forward to the update. Thanks!
@nmn this is not about type-safety, this is about not being able to get 100% coverage
@vkurchatkin agreed - i just ran into the same thing as i started upon the path of 100% coverage :(

grrr :-P
Most helpful comment
@nmn this is not about type-safety, this is about not being able to get 100% coverage