Skip to content

Instantly share code, notes, and snippets.

@junkor-1011
Last active December 15, 2024 09:31
Show Gist options
  • Save junkor-1011/e997242fe3849fc434c4f55ada503896 to your computer and use it in GitHub Desktop.
Save junkor-1011/e997242fe3849fc434c4f55ada503896 to your computer and use it in GitHub Desktop.
TypeScript ErrorHandling with Result Type Example

TypeScript ErrorHandling with Result Type Example

(todo)

{
"tasks": {
"dev": "deno run --watch main.ts"
},
"imports": {
"@std/assert": "jsr:@std/assert@1"
}
}
{
"version": "4",
"specifiers": {
"jsr:@std/assert@1": "1.0.8",
"jsr:@std/internal@^1.0.5": "1.0.5"
},
"jsr": {
"@std/[email protected]": {
"integrity": "ebe0bd7eb488ee39686f77003992f389a06c3da1bbd8022184804852b2fa641b",
"dependencies": [
"jsr:@std/internal"
]
},
"@std/[email protected]": {
"integrity": "54a546004f769c1ac9e025abd15a76b6671ddc9687e2313b67376125650dc7ba"
}
},
"workspace": {
"dependencies": [
"jsr:@std/assert@1"
]
}
}
export type SuccessResult<T> = {
readonly ok: true;
readonly value: T;
};
export type ErrorResult<E> = {
readonly ok: false;
readonly error: E;
};
export type Result<T, E> = SuccessResult<T> | ErrorResult<E>;
export function ok<T>(value: T): SuccessResult<T> {
return {
ok: true,
value,
};
}
export function err<E>(error: E): ErrorResult<E> {
return {
ok: false,
error,
};
}
export type ResultPromise<T, E> = Promise<Result<T, E>>;
import { assert, assertEquals } from "@std/assert";
import { err, ok, type Result } from "./lib.ts";
Deno.test("ok function creates an ErrorResult", () => {
const value = 12;
const result = ok(value);
assertEquals(result, { ok: true, value: 12 });
const complexValue = {
a: -10.5,
b: undefined,
c: "Hello, World",
d: false,
e: { x: 100, y: {}, z: null },
};
const complexResult = ok(complexValue);
assertEquals(complexResult, {
ok: true,
value: complexValue,
});
});
Deno.test("err function creates an ErrorResult", () => {
const result = err("error message");
assertEquals(result, { ok: false, error: "error message" });
const includeException = err(new Error("exception"));
assertEquals(includeException.ok, false);
assert(includeException.error instanceof Error);
});
Deno.test("Result type allows only SuccessResult or ErrorResult", () => {
const success: Result<number, string> = ok(42);
assertEquals(success.ok, true);
assertEquals(success.value, 42);
const failure: Result<number, string> = err("error");
assertEquals(failure.ok, false);
assertEquals(failure.error, "error");
});
export function add(a: number, b: number): number {
return a + b;
}
// Learn more at https://docs.deno.com/runtime/manual/examples/module_metadata#concepts
if (import.meta.main) {
console.log("Add 2 + 3 =", add(2, 3));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment