我正在尝试编写一个Javascript项目,其中包含严格的流式输入。我也依赖big-integer
。不幸的是,flow-typed
中没有预设的流量注释,谷歌也没有提供任何有用的主题。
像许多JavaScript包一样,big-integer
导出一个函数,通常称为bigInt
。这可以直接调用,如:bigInt(13)
,bigInt("134e134")
等,它创建大整数的对象(我决定将此函数的返回值的类型称为基于“BigInteger”的“类”)文档 - 但我不认为内部实际上使用类,因为我相信包在ES6之前出来了)。
这适用于函数的输出,我可以将方法附加到该类,我们都很好。然而,bigInt
本身有一些方法,例如bigInt.lcm(123, 234)
。我该如何记录这个?
declare module "big-integer-types" {
declare class BigInteger {
add(addend: BigIntInput): BigInteger;
minus(subtractand: BigIntInput): BigInteger;
/* snip */
}
declare type BigIntInput = number | string | BigInteger;
declare type BigIntFn = (void | number | string | BigInteger) => BigInteger;
}
declare module "big-integer" {
import type { BigIntFn } from "big-integer-types";
declare export default BigIntFn
}
这适用于大整数字段,例如用于类型检查bigInt(12).plus("144e53")
。哪个好。但这不包括bigInt.lcm(134, 1551)
,这会产生流量错误。
另一种方法是将big-integer
模块的导出声明为具有某些相关功能的类型。例如:
declare module "big-integer-types" {
declare type BigIntegerStaticMethods {
lcm(a: BigIntInput, b: BigIntInput): BigInteger,
/* snip */
}
declare type BigIntInput = number | string | BigInteger;
}
declare module "big-integer" {
import type BigIntegerStaticMethods from "big-integer-types";
declare export default BigIntegerStaticMethods
}
这适用于静态方法,但我不知道怎么说可以调用“类型”。所以我不知道如何同时实现这两个目标。
这看起来很奇怪,因为带有字段的函数在javascript中很常见,并且流文档表明他们经过了很多努力才能让类型系统支持使用javascript。所以我认为有一个流语法来实现这一点,我只是无法弄清楚它是什么,并且无法在文档中找到它。
您可以在类中声明一个未命名的静态函数:
declare type BigIntInput = number | string | BigInteger;
declare class BigInteger {
add(addend: BigIntInput): BigInteger;
minus(subtractand: BigIntInput): BigInteger;
static lcm(a: BigIntInput, b: BigIntInput): BigInteger;
static (data?: BigIntInput): BigInteger;
}
BigInteger.lcm(1,2);
BigInteger(4).add(5);