How to declare a stream type for numbers that excludes infinity and NaN?

The built-in type numberin the stream allows the use of "exotic" values, such as Infinity, -Infinityand NaN.

How can I make a type allow real numbers?

EDIT. It is not a question of how to check if a variable is a real number. It's about dialing with a thread.

I am looking for a way to write my functions, for example:

// @flow
function sum (x: real, y: real) { ... }

My question is how to determine the type real, so it works with Flow ( http://flowtype.org/ ).

+4
source share
2

. .

. : https://github.com/facebook/flow/issues/1406

, , NaN/Infinity , , .

,

Number.MAX_VALUE + Number.MAX_VALUE === Infinity
-Number.MAX_VALUE - Number.MAX_VALUE === -Infinity
Number.MAX_VALUE * 2 === Infinity
Number.MAX_VALUE / 0.5 === Infinity

Flow - , . , .

+3

, Flow. , , , , Flow , . :

// @flow

// Define `Int` as an opaque type.  Internally, it just a number.
// It opaque because only this module can produce values of
// this kind, so in order to obtain an "Int", one _must_ use one of
// these functions, which (at runtime) will guarantee that these
// will always be integers.
export opaque type Int = number;

// Here a function that will convert any number to an Int by running
// a typecheck at runtime and perhaps change the value (by rounding)
// This is the ONLY way of obtaining a value of the type Int   
export function int(n: number): Int {
    if (!Number.isFinite(n)) {
        throw new Error('Not a (finite) number');
    }

    // Round any real numbers to their nearest int
    return Math.round(n);
}

// In your private functions, you can now require Int inputs
export function isPrime(n: Int): boolean {
    // In here, you can assume the value of `n` is guaranteed to be an Integer number
    for (let i = 2; i < Math.sqrt(n); i++) {
        if (n % i === 0) return false;
    }
    return true;
}

:

// @flow

import { int, isPrime } from './lib';

isPrime(int(NaN));   // ok, but a runtime error, because NaN is not a number!
isPrime(int(3.14));  // ok, will effectively become isPrime(3)
isPrime(3.14);       // Flow error!
0

All Articles