代码之家  ›  专栏  ›  技术社区  ›  bsr

如何为联合类型编写reasonml绑定

  •  3
  • bsr  · 技术社区  · 8 年前

    我正在为你写绑定 https://github.com/oblador/react-native-keychain/blob/master/typings/react-native-keychain.d.ts#L76

    getGenericPassword返回 false 如果一个错误,否则 object ( credentials Promise<boolean | credentials> Js.Promise.t(option(credentials)) 在绑定文件中。下面是一个模板。

    谢谢你的帮助。

    [@bs.deriving abstract]
    type credentials = {
      service: string,
      username: string,
      password: string,
    };
    
    /* TODO convert the actual return value 
    Js.Promise.t(option(credentials)) to more reason type 
    Js.Promise.t(option(credentials)) */
    
    [@bs.module "react-native-keychain"] [@bs.scope "default"]
    external getGenericPassword: unit => Js.Promise.t(option(credentials)) = "";
    
    1 回复  |  直到 8 年前
        1
  •  8
  •   glennsl Namudon'tdie    8 年前

    你可以用 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 .