Dev Helpers
← Back

Narrow an array to successes

Narrow an array to successes using TypeScript.

Open this example in the interactive library

Source code

type Result =
  { kind: "ok"; value: number } | { kind: "error"; message: string };
const results: Result[] = [
  { kind: "ok", value: 3 },
  { kind: "error", message: "offline" },
];
console.log(
  results
    .filter((r): r is Extract<Result, { kind: "ok" }> => r.kind === "ok")
    .map((r) => r.value),
);

Sample output

[ 3 ]