Flow - How to check a range of numbers?

I saw that Flow can check a set of possible values , but I don't know how I can check a possible range of numbers.

When I used the prop-types module, I could do a spot check , but in a thread, I don't know how I can do something like this.

Can anyone help me?

+3


source to share


1 answer


In case anyone finds this, I am adding an answer that allows you to validate a range of numbers, but requires additional types to be created to represent this information.

Side effects are that, with some upfront cost, you get both runtime and compile time.

Here's flow.org/try link as a demo.

Let's say I want to make sure the numbers passed between them are between 0 and 5.

// Create a type that we can use for validation
type WithinRange = {};

// Create our extended number type
type RangedNumber = number & WithinRange;

// Validation function that works 
function makeRangeCheckedNumber(x: number): ?RangedNumber {
  if (x > 0 && x < 5) {
    // type cast to any so we can type cast back to RangedNumber
    return ((x: any): RangedNumber);
  } else {
    return null;
  }
}

// function that were to take the range checked number
function someComputation(num: RangedNumber): void {
}

const myInputNumber = 5;


// So we have to wrap it in the validation function we wrote up
const maybeWithinRangeInput = makeRangeCheckedNumber(myInputNumber);

// And this would force users of someComputation to handle both cases
if (maybeWithinRangeInput == null) {
  throw new Error();
} else {
  someComputation(maybeWithinRangeInput);
}

      

Assuming you are removing thread types in production assemblies, all thread types will be removed and you are left with runtime checking functionality.



Your React component can now use RangedNumber, and

type Props = {
  input: RangedNumber
}

class MyComponent extends React.Component {
  props: Props
  ...
}

      

And anyone who wants to use your component will have to use the validation function when calling your component.

// Would error until they wrap this in makeRangeCheckedNumber
<MyComponent input={6} />

// This is fine
<MyComponent input={makeRangeCheckedNumber(6)} />

      

This forces consumers to call the validation function instead of doing it automatically, but Flow will let them know and you can ensure that your code is correct.

+3


source







All Articles