@ucios/ts-result
v0.2.0
Published
A package that brings Result Type that can be used in TypeScript projects to help with error management
Maintainers
Readme
@ucios/ts-result
A lightweight TypeScript Result type for explicit error handling. Inspired by Rust's Result<T, E> pattern, this package provides a type-safe way to handle operations that can fail without relying on exceptions.
Why Use Result Types?
- Explicit error handling - Forces you to handle both success and failure cases
- Type safety - Full TypeScript support with discriminated unions
- No exceptions - Avoid try/catch blocks for expected failures
- Self-documenting - Function signatures clearly indicate possible failures
Installation
npm install @ucios/ts-resultyarn add @ucios/ts-resultpnpm add @ucios/ts-resultUsage
Basic Example
import { Result, ResultGen } from "@ucios/ts-result";
function divide(a: number, b: number): Result<number, string> {
if (b === 0) {
return ResultGen.failed("Division by zero");
}
return ResultGen.succeed(a / b);
}
const result = divide(10, 2);
if (result.success) {
console.log("Result:", result.data); // Result: 5
} else {
console.log("Error:", result.error);
}Working with Different Types
import { Result, ResultGen } from "@ucios/ts-result";
// Success with different data types
const numberResult = ResultGen.succeed(42);
const stringResult = ResultGen.succeed("hello");
const objectResult = ResultGen.succeed({ id: 1, name: "John" });
// Failure with custom error types
interface ValidationError {
field: string;
message: string;
}
const failure = ResultGen.failed<ValidationError>({
field: "email",
message: "Invalid email format",
});Type Narrowing
The Result type is a discriminated union, so TypeScript automatically narrows the type based on the success property:
import { Result, ResultGen } from "@ucios/ts-result";
function parseJson<T>(json: string): Result<T, Error> {
try {
return ResultGen.succeed(JSON.parse(json) as T);
} catch (e) {
return ResultGen.failed(e instanceof Error ? e : new Error(String(e)));
}
}
const result = parseJson<{ name: string }>('{"name": "Alice"}');
if (result.success) {
// TypeScript knows `result` is Success<T> here
console.log(result.data.name); // "Alice"
} else {
// TypeScript knows `result` is Failure<Error> here
console.log(result.error.message);
}Real-World Example: API Call
import { Result, ResultGen } from "@ucios/ts-result";
interface User {
id: number;
name: string;
email: string;
}
interface ApiError {
code: number;
message: string;
}
async function fetchUser(id: number): Promise<Result<User, ApiError>> {
try {
const response = await fetch(`/api/users/${id}`);
if (!response.ok) {
return ResultGen.failed({
code: response.status,
message: `Failed to fetch user: ${response.statusText}`,
});
}
const user = (await response.json()) as User;
return ResultGen.succeed(user);
} catch {
return ResultGen.failed({
code: 0,
message: "Network error",
});
}
}
// Usage
const userResult = await fetchUser(123);
if (userResult.success) {
console.log(`Welcome, ${userResult.data.name}!`);
} else {
console.error(`Error ${userResult.error.code}: ${userResult.error.message}`);
}API Reference
Types
Result<T, E>
A discriminated union type representing either a successful result or a failure.
type Result<T, E> = Success<T> | Failure<E>;T- The type of the success valueE- The type of the error value
Success<T>
Represents a successful result.
| Property | Type | Description |
| --------- | ------ | ------------------------- |
| success | true | Always true for success |
| data | T | The success value |
Failure<E>
Represents a failed result.
| Property | Type | Description |
| --------- | ------- | -------------------------- |
| success | false | Always false for failure |
| error | E | The error value |
ResultGen
A utility class for creating Result instances.
ResultGen.succeed<T>(data: T): Success<T>
Creates a successful result.
const result = ResultGen.succeed({ id: 1, name: "John" });
// result.success === true
// result.data === { id: 1, name: "John" }ResultGen.failed<E>(error: E): Failure<E>
Creates a failed result.
const result = ResultGen.failed("Something went wrong");
// result.success === false
// result.error === "Something went wrong"Requirements
- TypeScript 4.7+ (for full type inference support)
- ES2020+ runtime environment
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Development
# Install dependencies
npm install
# Run tests
npm test
# Build
npm run build
# Format code
npm run format
# Check formatting
npm run check-formatLicense
MIT © Leon Adarcewicz
