I am trying to find out how to properly type a custom assert function
import assert from 'assert'
addCommand(first: string | CommandDefinition, second?: CommandHandler) {
let cmd: CommandDefinition
if (typeof first === 'string') {
// GOOD
if(!second) throw Error()
// BAD
// assert(second)
cmd = {id: first, handler: second}
In the GOOD version of the code above there are no Flow errors because the guard is detected. However using an assert as guard is not detected by Flow.
Is there a way to teach Flow that the BAD version is actually OK?
Can you be more specific? I guess you want to make sure that cmd.handler is CommandHander, and not ?CommandHandler?
As a workaround, you can cast it to any and then back to CommandHandler: ((second: any): CommandHandler) after the assertion.
Here is a workaround:
import invariant from 'assert'
declare var x: ?string;
invariant(x);
x.toLowerCase();
Function with name invariant is hardcoded in Flow to provide such behavior
Most helpful comment
Here is a workaround:
Function with name
invariantis hardcoded in Flow to provide such behavior