flowtype

Flowtype: How to create type guard function?


I want to use type refinements from function. How to create type guard function (TypeScript) in flow?

I TypeScript example:

function isString(arg: Showable): arg is string {
    return typeof arg === 'string';
}

II Flow

/* @flow */
type Showable = number | string;

// ok
function barOk (arg: Showable) {
  return typeof arg === 'string' ? arg.length : (arg + 1);
}

// type guard function
function isString(arg: Showable) {
    return typeof arg === 'string';
}

// Error
function barError (arg: Showable) {
  return isString(arg) ? arg.length : (arg + 1);
                         // ^ Cannot get `arg.length` because property `length` is missing in `Number`
}

Solution

  • Change your isString function to the following:

    function isString(arg: Showable): boolean %checks {
        return typeof arg === 'string';
    }
    

    See Predicate Functions