Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flowtype: How to create type guard function?

Tags:

flowtype

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`
}
like image 428
Buggy Avatar asked Sep 25 '26 09:09

Buggy


1 Answers

Change your isString function to the following:

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

See Predicate Functions

like image 173
Tom Cumming Avatar answered Sep 29 '26 01:09

Tom Cumming



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!