Skip to content

feat(result): add unwrap and expect functions#37

Merged
dylnslck merged 1 commit into
ByteSliceHQ:mainfrom
coderdan:feat/result-unwrap-expect
Jun 28, 2026
Merged

feat(result): add unwrap and expect functions#37
dylnslck merged 1 commit into
ByteSliceHQ:mainfrom
coderdan:feat/result-unwrap-expect

Conversation

@coderdan

Copy link
Copy Markdown
Contributor

Summary

Adds Rust-inspired unwrap and expect escape hatches to @byteslice/result, for the cases where a caller knows an operation should have succeeded and just wants the underlying data.

  • unwrap(result) — returns the success data, or re-throws the failure's underlying Error.
  • expect(result, message) — returns the success data, or throws a new Error(message, { cause }), preserving the original error's stack trace via cause (consistent with how the existing docs treat errors).

Both handle both FailureOption shapes (a bare Error and the { error: Error } custom-failure object).

Design note

Result is modelled as a plain discriminated union (not a class), and the public API is free functions like withResult. To stay consistent, these are free functions (unwrap(result)) rather than methods (result.unwrap()) — keeping Result a plain, serializable object. If you'd prefer method-style chaining, that's a larger design shift worth discussing separately.

A small internal isSuccess type guard is used because, with a generic failure type F, TypeScript won't narrow the union on result.failure === undefined directly.

Testing

  • Added unit tests covering success, failure re-throw, custom-failure unwrapping, expect's message, and cause preservation.
  • bun test (13 pass), biome ci, cspell, and tsup build all pass.

Changeset

Included a minor changeset (new backward-compatible features).

Inspired by Rust's Result, unwrap returns the success data or re-throws
the failure's underlying error, while expect does the same but throws an
error with a caller-provided message (preserving the original via cause).
@changeset-bot

changeset-bot Bot commented Jun 28, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: e021f2e

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 3 packages
Name Type
@byteslice/result Minor
@byteslice/events Patch
@byteslice/playground Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@dylnslck dylnslck left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚀

@dylnslck dylnslck merged commit 0967506 into ByteSliceHQ:main Jun 28, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants