try-error Documentation

TypeScript Types Reference

Complete reference for all TypeScript types, interfaces, and utilities in try-error

Core Types

TryError<T>

The main error interface that extends the standard Error with additional context and metadata.

TryError Interfacetypescript
interface TryError<T = any> extends Error {
  readonly type: string;
  readonly message: string;
  readonly stack?: string;
  readonly source: string;
  readonly timestamp: number;
  readonly context?: T;
  readonly cause?: Error | TryError;
}

Properties

  • type - Error classification (e.g., 'ValidationError', 'NetworkError')
  • message - Human-readable error description
  • stack - Stack trace (optional)
  • source - Source location where error was created
  • timestamp - Unix timestamp when error occurred
  • context - Additional error context data
  • cause - Original error that caused this error

TryResult<T, E>

Union type representing either a successful result or an error.

TryResult Typetypescript
type TryResult<T, E extends TryError = TryError> = T | E;

Type Parameters

  • T - The success value type
  • E - The error type (defaults to TryError)

TryTuple<T, E>

Go-style tuple return type for functions that prefer tuple destructuring.

TryTuple Typetypescript
type TryTuple<T, E extends TryError = TryError> = [T, null] | [null, E];

Usage Example

TryTuple Usagetypescript
const [user, error] = await tryAsyncTuple(() => fetchUser('123'));
if (error) {
  console.error('Failed:', error.message);
} else {
  console.log('Success:', user.name);
}

Utility Types

TrySuccess<T>

Type alias for successful results, excluding error types.

TrySuccess Typetypescript
type TrySuccess<T> = T extends TryError ? never : T;

TryFailure<E>

Type alias for error results, excluding success types.

TryFailure Typetypescript
type TryFailure<E extends TryError = TryError> = E;

UnwrapTry<T>

Extracts the success type from a TryResult, useful for type inference.

UnwrapTry Typetypescript
type UnwrapTry<T> = T extends TryResult<infer U, any> ? U : T;

Example

UnwrapTry Exampletypescript
type UserResult = TryResult<User, TryError>;
type UserType = UnwrapTry<UserResult>; // User

UnwrapTryError<T>

Extracts the error type from a TryResult.

UnwrapTryError Typetypescript
type UnwrapTryError<T> = T extends TryResult<any, infer E> ? E : never;

Function Types

TryFunction<T>

Type for synchronous functions that may throw errors.

type TryFunction<T> = () => T;

TryAsyncFunction<T>

Type for asynchronous functions that may throw errors.

type TryAsyncFunction<T> = () => Promise<T>;

TryErrorFactory<T>

Type for functions that create TryError instances.

type TryErrorFactory<T = any> = (
  type: string,
  message: string,
  context?: T,
  cause?: Error | TryError
) => TryError<T>;

Type Guards

isTryError

Type guard function to check if a value is a TryError.

function isTryError<T = any>(value: unknown): value is TryError<T> {
  return (
    typeof value === 'object' &&
    value !== null &&
    'type' in value &&
    'message' in value &&
    'source' in value &&
    'timestamp' in value
  );
}

Usage

const result = await tryAsync(() => fetchUser('123'));
if (isTryError(result)) {
  // TypeScript knows result is TryError
  console.error(result.message);
} else {
  // TypeScript knows result is User
  console.log(result.name);
}

isTrySuccess

Type predicate to check if a TryResult is successful.

function isTrySuccess<T, E extends TryError>(
  result: TryResult<T, E>
): result is TrySuccess<T> {
  return !isTryError(result);
}

Advanced Types

Conditional Error Types

Advanced conditional types for complex error handling scenarios.

// Extract error type based on condition
type ExtractError<T, K extends string> = T extends TryError
  ? T['type'] extends K
    ? T
    : never
  : never;

// Map multiple error types
type ErrorMap<T extends Record<string, any>> = {
  [K in keyof T]: TryError<T[K]> & { type: K };
}[keyof T];

// Combine multiple TryResults
type CombineTryResults<T extends readonly TryResult<any, any>[]> = {
  [K in keyof T]: T[K] extends TryResult<infer U, any> ? U : never;
};

Generic Constraints

Common generic constraints used throughout the library.

// Ensure T is not a TryError
type NonError<T> = T extends TryError ? never : T;

// Ensure T extends TryError
type ErrorOnly<T> = T extends TryError ? T : never;

// Ensure T is serializable
type Serializable = string | number | boolean | null | undefined | 
  { [key: string]: Serializable } | Serializable[];

// Context constraint
type ErrorContext = Record<string, Serializable> | Serializable;

Module Declarations

Type declarations for extending try-error functionality.

// Extend global Error interface
declare global {
  interface Error {
    toTryError?(): TryError;
  }
}

// Module augmentation for custom error types
declare module 'try-error' {
  interface TryErrorTypeMap {
    ValidationError: { field: string; value: unknown };
    NetworkError: { url: string; status?: number };
    AuthenticationError: { userId?: string };
    AuthorizationError: { resource: string; action: string };
    NotFoundError: { id: string; type: string };
    ConflictError: { field: string; value: unknown };
    RateLimitError: { limit: number; window: number };
  }
}

// Utility type for mapped error types
type MappedTryError<K extends keyof TryErrorTypeMap> = TryError<TryErrorTypeMap[K]> & {
  type: K;
};

Practical Examples

API Response Types

// Define API response types
interface User {
  id: string;
  name: string;
  email: string;
}

interface ApiError {
  code: string;
  details?: Record<string, unknown>;
}

// Function return types
type FetchUserResult = TryResult<User, TryError<ApiError>>;
type CreateUserResult = TryResult<User, TryError<ApiError>>;

// Usage
async function fetchUser(id: string): Promise<FetchUserResult> {
  return tryAsync(async () => {
    const response = await fetch(`/api/users/${id}`);
    if (!response.ok) {
      throw createTryError('ApiError', 'Failed to fetch user', {
        code: 'FETCH_FAILED',
        details: { userId: id, status: response.status }
      });
    }
    return response.json();
  });
}

Service Layer Types

// Service interface with try-error
interface UserService {
  findById(id: string): Promise<TryResult<User, TryError>>;
  create(data: CreateUserData): Promise<TryResult<User, TryError>>;
  update(id: string, data: UpdateUserData): Promise<TryResult<User, TryError>>;
  delete(id: string): Promise<TryResult<void, TryError>>;
}

// Implementation with specific error types
class UserServiceImpl implements UserService {
  async findById(id: string): Promise<TryResult<User, TryError>> {
    return tryAsync(async () => {
      const user = await this.repository.findById(id);
      if (!user) {
        throw createTryError('NotFoundError', `User ${id} not found`, {
          id,
          type: 'user'
        });
      }
      return user;
    });
  }
}

Related Pages

Error Types

Learn about the core error type concepts

View Error Types →

API Reference

Complete API documentation

View API Reference →

React Types

TypeScript types for React integration

View React Types →