Flow: Control flow ignored with assert

Created on 9 Apr 2017  路  2Comments  路  Source: facebook/flow

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?

Most helpful comment

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

All 2 comments

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

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Beingbook picture Beingbook  路  3Comments

mjj2000 picture mjj2000  路  3Comments

glenjamin picture glenjamin  路  3Comments

ghost picture ghost  路  3Comments

mmollaverdi picture mmollaverdi  路  3Comments