你可以用
Js.Types.classify
type maybeCredentials;
[@bs.module "react-native-keychain"] [@bs.scope "default"]
external getGenericPassword: unit => Js.Promise.t(maybeCredentials) = "";
let getGenericPassword: unit => Js.Promise.t(option(credentials)) =
() =>
Js.Promise.(
getGenericPassword()
|> then_(maybeCredentials =>
switch (Js.Types.classify(maybeCredentials)) {
| JSObject(obj) => resolve(Some(obj |> Obj.magic))
| _ => resolve(None)
}
)
);
在这里
maybeCredentials
定义并用作中间类型。
然后,我们定义一个与绑定同名的函数,它将“隐藏”该名称,并防止直接使用绑定来支持我们的“重写”。然而,
在内部
覆盖我们仍然可以使用绑定。
Js.Types.classify分类
获取返回值的运行时类型。如果它是我们使用的对象
Obj.magic
obj_type
给我们的
credentials
类型(从函数的返回类型推断),并将其包装为
option
. 对于其他类型,我们返回
None
.
顺便说一下,这种“类型”称为未标记的并集。我写了几个例子,用不同的策略来处理这些问题,作为一个生产者和消费者
bucklescript-cookbook
.