From a6edb3505b49b164a07b31c641ccf51c1da3c121 Mon Sep 17 00:00:00 2001 From: Anton Nesterov Date: Sat, 19 Oct 2024 15:50:34 +0200 Subject: [PATCH] docs --- grip.ts | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/grip.ts b/grip.ts index 81ed875..ca37ed8 100644 --- a/grip.ts +++ b/grip.ts @@ -9,6 +9,9 @@ interface Status { of(cls: any): boolean; } +/** + * Error result + */ export class Err extends Error { Ok() { return false; @@ -36,6 +39,9 @@ export class Err extends Error { } } +/** + * Successful result + */ export class Ok { Ok() { return true; @@ -148,14 +154,27 @@ type Unwrap = ? U : T; -export type SafeResult = +type SafeResult = T extends Promise ? Promise>> : T extends () => Promise ? Promise>> : Result>; -export function grip(action: T) { +/** + * Grip wraps functions, promises or generators and returns it as a result. + * The result can be handled as an object { value, status }, or as a tuple [value, object]. + * The result and status interfaces have the methods `ok(), fail(), of(Error)` to check the status: + * + * ```javascript + * const json = grip(response.body.joson()) + * if (json.of(SyntaxError)) { + * // handle parse error + * } + * // handle json.value + * ``` + */ +export function grip(action: T): SafeResult { if (action instanceof Promise) { return promise(action) as SafeResult; }