有一点中间地带,你可以用这个与流罢工。是的,您需要使用运行时检查来最终解决这个问题,但是您可以构建一个不透明的类型,以使Flow强制您不能绕过这些验证函数。首先,在一个文件中,把这个:
// @flow
// Define `Int` as an opaque type. Internally, it's just a number.
// It's 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's 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-9] +'。你也可以使用'typeof'或'isNaN()' – vaso123
@lolka_bolka你能提供一个正则表达式的例子吗? (我宁愿不依赖于已知是越野车的原生类型。) –
也许这是http://stackoverflow.com/questions/4724555/how-do-i-check-if-a-number-evaluates-to -infinity – maioman