Flow: Function-based type refinement?

Created on 18 Oct 2017  路  8Comments  路  Source: facebook/flow

I was wondering if this feature is possible, or is something planned for the future of flow?

As an example (tryflow link):

// @flow

function isString(value: any) {
    return typeof value === 'string'
}

// has error, becuase flow doesn't know we've refined type of `obj.value` to string
function getString(obj: { value: string | number }): string {
  if (isString(obj.value)) {
    return obj.value
  } else {
    return 'default value'
  }
}
// flow understands inline `typeof obj.value === 'string'` for type refinement
// so, no error
function getString(obj: { value: string | number }): string {
  if (typeof obj.value === 'string') {
    return obj.value
  } else {
    return 'default value'
  }
}

I was hoping isString would refine the type of obj.value in the same way typeof obj.value === 'string' does.

refinements

Most helpful comment

Cool, sounds like the limitations are at least known. Is there a roadmap I could track, or any plans for building out functionality for %checks?

All 8 comments

See #5087

Wow! Exactly what I was looking for 馃槃 . is it possible to use %checks in libdefs? For example, I tried adding %checks to isNil within the lodash type definitions, and I get a runtime error from flow.

What version of flow? Can you reproduce the error on https://flow.org/try ?

Seems like the issue might be the fact that the function is treated as a class method. Should %checks work for class methods?
tryflow

cc @panagosg7

You cannot use %checks in Flow libdefs. You cannot have multiple predicate methods on an object either. See #4948 and #4254 for additional issues with %checks.

Unfortunately, %checks is not yet supported for methods.

Cool, sounds like the limitations are at least known. Is there a roadmap I could track, or any plans for building out functionality for %checks?

Was this page helpful?
0 / 5 - 0 ratings