LearnTypesOptional and fallible types

Optional and fallible types

Show missing values and errors in the type.

Optional values and fallible values are normal types. They make absence and failure part of the function contract.

let option := import "@std/option";
let result := import "@std/result";
let Option := option.Option;
let Result := result.Result;

let findPort () : Option[Int] := option.someOf[Int](8080);

let parsePort () : Result[Int, String] :=
  result.ok[Int, String](8080);

parsePort();

Optional type shape

let option := import "@std/option";
let Option := option.Option;

let findPort () : Option[Int] := option.someOf[Int](8080);

A caller can see from the result type that the value may be missing.

Fallible type shape

let result := import "@std/result";
let Result := result.Result;

let parsePort () : Result[Int, String] := result.ok[Int, String](8080);

A caller can see both the success type and the error type.

Use helpers for simple paths

let configured := findPort();
let parsed := parsePort();

configured.unwrapOr[Int](3000);
parsed.unwrapOr[Int, String](3000);

Use match when missing and error cases need different policy.