You can use the Shapes::idx
method as you mentioned in your answer.
but you can also use null coalesce operator, which you might be more familiar with from other programming languages such as PHP and C#.
see : https://docs.hhvm.com/hack/expressions-and-operators/coalesce
example :
type Foo = shape(
'bar' => ?int,
?'baz' => int,
);
function qux(Foo $foo): int {
$default = 1;
// foo[bar] is null ? set default.
$bar = $foo['bar'] ?? $default;
// foo[baz] doesn't exist ? set default.
$baz = $foo['baz'] ?? $default;
return $baz + $bar;
}
<<__EntryPoint>>
async function main(): Awaitable<noreturn> {
echo qux(shape(
'bar' => null,
)); // 2
echo qux(shape(
'bar' => 0,
)); // 1
echo qux(shape(
'bar' => 1,
)); // 2
echo qux(shape(
'bar' => 4,
'baz' => 2,
)); // 6
echo qux(shape(
'bar' => null,
'baz' => 0
)); // 1
}
Hack also support null coalesce equal operator.
example :
// foo[bar] is null ? set foo[bar] to default
$foo['bar'] ??= $default;
// foo[baz] is missing ? set foo[baz] to default
$foo['baz'] ??= $default;