无法理解复杂的类型并对其进行分解-Reasonml

时间:2019-04-02 13:10:30

标签: reason reason-react

我使用原因阿波罗从服务器获取数据。它返回给我类型的数据(vscode向我显示这种类型):

option(
  Js.t(
    < count : int;
  rows : [ `User of
             < firstName : string; id : string; lastName : string;
               userName : string >
             Js.t
         | `Node of < id : string > Js.t ] option Js.Array.t >
  )
)

我不太了解“行”的类型,因此我无法从中获取数据。我尝试过:

switch response##users {
   | None => ReasonReact.string("none")
   | Some(data) => {
      data##rows |> Array.map(optionalRow => {
         switch optionalRow {
            | None => ReasonReact.string("none")
            | Some(row) => ReasonReact.string(row##firstName);   
         }
      });
      ReasonReact.string("test");
   }
};

但是出现以下错误:

This has type:
  array(option(Js.t(({.. firstName: string} as 'a)))) =>
  array(ReasonReact.reactElement)
But somewhere wanted:
  Js.Array.t(option([ `Node({. "id": string})
                    | `User({. "firstName": string, "id": string,
                              "lastName": string, "userName": string}) ])) =>
  'b

The incompatible parts:
  array(option(Js.t('a)))
  vs
  Js.Array.t(option([ `Node({. "id": string})
                    | `User({. "firstName": string, "id": string,
                              "lastName": string, "userName": string}) ]))
    (defined as
    array(option([ `Node({. "id": string})
                 | `User({. "firstName": string, "id": string,
                           "lastName": string, "userName": string}) ])))

  Further expanded:
    Js.t('a)
    vs
    [ `Node({. "id": string})
    | `User({. "firstName": string, "id": string, "lastName": string,
              "userName": string}) ]

如何从结果中获取“名字”?

1 个答案:

答案 0 :(得分:0)

很清楚,这是一个多形变体,下面是如何获取名字的代码段。

...
switch optionalRow {
   | None => ReasonReact.string("none")
   | Some(row) => {
      switch row {
         | `User(u) => ReasonReact.string(u##firstName)
         | `Node(n) => ReasonReact.string("test")
      };
      ReasonReact.string("test");
   }
}
...