hacklang

How to access optional shape field in hack?


To give an example, let's assume I have a type foo of the following shape,

type foo = shape(
  ?'bar' => float,
  ...
);

Now if I try to access value of field bar in the following way,

do_something_with($rcvd['bar']);

where $rcvd is of foo type, it doesn't work as bar is an optional member and might not exist for the instance $rcvd. So for this given example, the question would be - how to access the member bar of $rcvd?


Solution

  • Ok, found it: https://docs.hhvm.com/hack/reference/class/HH.Shapes/idx/

    So the correct way is,

    Shapes::idx($rcvd, 'bar');