/** * @file Types Index * @description Central export for all shared types, utility types, and type helpers * @module @/types * * This module provides: * - API types for request/response handling * - Branded types for type-safe identifiers * - Utility types for common TypeScript patterns * - Conditional type helpers for enhanced inference * * @example * ```typescript * import type { UserId, ApiResponse, DeepPartial } from '@/types'; * * const userId: UserId = 'user_123' as UserId; * const response: ApiResponse = await fetchUser(userId); * ``` */ import type * as React from 'react'; export type { ApiResponse, ApiResponseMeta, PaginationMeta, PaginatedResponse, ApiErrorResponse, PaginationParams, SortParams, FilterParams, ListQueryParams, Timestamps, SoftDelete, BaseEntity, UserRef, AuditFields, FileUploadResponse, BatchOperationResponse, HealthCheckResponse, ApiSuccessResponse, ApiFailureResponse, HttpStatusCode, CacheControl, RateLimitInfo, ValidationError, ValidationErrorResponse, } from './api'; /** * Brand symbol for creating nominal types * @internal */ declare const __brand: unique symbol; /** * Branded type - creates a nominal type that is incompatible with its base type * * This pattern prevents accidental type confusion between semantically different * values that share the same structural type (e.g., UserId vs PostId, both strings) * * @template T - The base type to brand * @template Brand - A unique brand identifier * * @example * ```typescript * type UserId = Branded; * type PostId = Branded; * * const userId: UserId = 'user_123' as UserId; * const postId: PostId = 'post_456' as PostId; * * // This would be a compile error: * // const invalid: UserId = postId; * ``` */ export type Branded = T & { readonly [__brand]: Brand; }; /** * User identifier - branded string type * * @example * ```typescript * const userId: UserId = createUserId('usr_abc123'); * ``` */ export type UserId = Branded; /** * Organization identifier - branded string type */ export type OrganizationId = Branded; /** * Session identifier - branded string type */ export type SessionId = Branded; /** * API key - branded string type for sensitive credentials */ export type ApiKey = Branded; /** * Access token - branded string type for JWT/OAuth tokens */ export type AccessToken = Branded; /** * Refresh token - branded string type */ export type RefreshToken = Branded; /** * Email address - branded string type */ export type Email = Branded; /** * UUID - branded string type for universally unique identifiers */ export type UUID = Branded; /** * ISO 8601 datetime string - branded type for date/time values */ export type ISODateString = Branded; /** * URL string - branded type for validated URLs */ export type URLString = Branded; /** * Positive integer - branded number type */ export type PositiveInteger = Branded; /** * Percentage value (0-100) - branded number type */ export type Percentage = Branded; /** * Create a UserId from a string * * @param id - The raw string identifier * @returns A branded UserId * * @example * ```typescript * const userId = createUserId('usr_abc123'); * ``` */ export declare function createUserId(id: string): UserId; /** * Create a UUID from a string * * @param id - The raw UUID string * @returns A branded UUID * @throws {Error} If the string is not a valid UUID format */ export declare function createUUID(id: string): UUID; /** * Create an Email from a string * * @param email - The raw email string * @returns A branded Email * @throws {Error} If the string is not a valid email format */ export declare function createEmail(email: string): Email; /** * Create an ISODateString from a Date or string * * @param date - The date to convert * @returns A branded ISODateString */ export declare function createISODateString(date: Date | string): ISODateString; /** * Prettify a type for better IntelliSense display * * Flattens intersected types into a single object type for cleaner * tooltips in IDE hover information * * @template T - The type to prettify * * @example * ```typescript * type Merged = { a: string } & { b: number }; * type Pretty = Prettify; * // Displays as: { a: string; b: number } * ``` */ export type Prettify = { [K in keyof T]: T[K]; } & {}; /** * Deep partial type - makes all properties optional recursively * * Unlike Partial, this works on nested object properties * * @template T - The type to make deeply partial * * @example * ```typescript * interface User { * name: string; * profile: { bio: string; avatar: string }; * } * type PartialUser = DeepPartial; * // { name?: string; profile?: { bio?: string; avatar?: string } } * ``` */ export type DeepPartial = T extends object ? { [P in keyof T]?: DeepPartial; } : T; /** * Deep required type - makes all properties required recursively * * Opposite of DeepPartial, ensures all nested properties are required * * @template T - The type to make deeply required */ export type DeepRequired = T extends object ? { [P in keyof T]-?: DeepRequired; } : T; /** * Deep readonly type - makes all properties readonly recursively * * Ensures immutability at all levels of a nested object * * @template T - The type to make deeply readonly * * @example * ```typescript * const config: DeepReadonly = loadConfig(); * // config.nested.value = 'new'; // Error: Cannot assign to readonly property * ``` */ export type DeepReadonly = T extends object ? { readonly [P in keyof T]: DeepReadonly; } : T; /** * Make specific keys optional while keeping others required * * @template T - The object type * @template K - The keys to make optional * * @example * ```typescript * interface User { id: string; name: string; email: string } * type CreateUser = PartialBy; * // { id?: string; name: string; email: string } * ``` */ export type PartialBy = Prettify & Partial>>; /** * Make specific keys required while keeping others as-is * * @template T - The object type * @template K - The keys to make required * * @example * ```typescript * interface Config { host?: string; port?: number } * type RequiredConfig = RequiredBy; * // { host: string; port?: number } * ``` */ export type RequiredBy = Prettify & Required>>; /** * Extract the value type from a Record type * * @template T - A Record type * * @example * ```typescript * type UserRecord = Record; * type UserType = ValueOf; // User * ``` */ export type ValueOf = T[keyof T]; /** * Extract array element type * * @template T - An array type * * @example * ```typescript * type Users = User[]; * type SingleUser = ArrayElement; // User * ``` */ export type ArrayElement = T extends readonly (infer E)[] ? E : never; /** * Create a union type from array values (for const arrays) * * @template T - A readonly array type * * @example * ```typescript * const roles = ['admin', 'user', 'guest'] as const; * type Role = ArrayValues; // 'admin' | 'user' | 'guest' * ``` */ export type ArrayValues = T[number]; /** * Exclude null and undefined from a type * * @template T - The type to make non-nullable */ export type NonNullableDeep = T extends object ? { [P in keyof T]: NonNullableDeep>; } : NonNullable; /** * Extract keys of a type that match a value type * * @template T - The object type * @template V - The value type to match * * @example * ```typescript * interface User { id: string; name: string; age: number } * type StringKeys = KeysOfType; // 'id' | 'name' * ``` */ export type KeysOfType = { [K in keyof T]: T[K] extends V ? K : never; }[keyof T]; /** * Pick properties of a specific type * * @template T - The object type * @template V - The value type to pick * * @example * ```typescript * interface User { id: string; name: string; age: number } * type StringProps = PickByType; // { id: string; name: string } * ``` */ export type PickByType = Pick>; /** * Omit properties of a specific type * * @template T - The object type * @template V - The value type to omit */ export type OmitByType = Omit>; /** * Make properties mutable (remove readonly) * * @template T - The type with readonly properties */ export type Mutable = { -readonly [P in keyof T]: T[P]; }; /** * Deep mutable type - removes readonly from all nested properties * * @template T - The type to make mutable */ export type DeepMutable = T extends object ? { -readonly [P in keyof T]: DeepMutable; } : T; /** * Extract parameter types from a function * * @template T - A function type */ export type FunctionParameters unknown> = Parameters; /** * Extract return type from a function, unwrapping Promise if async * * @template T - A function type * * @example * ```typescript * async function fetchUser(): Promise { ... } * type Result = AsyncReturnType; // User * ``` */ export type AsyncReturnType unknown> = ReturnType extends Promise ? R : ReturnType; /** * Create a typed event handler function type * * @template E - The event type * * @example * ```typescript * type ClickHandler = EventHandler; * ``` */ export type EventHandler = (event: E) => void; /** * Callback function with typed result * * @template T - The result type * @template E - The error type (defaults to Error) */ export type Callback = (error: E | null, result?: T) => void; /** * Check if type T is exactly type U (not just assignable) * * @template T - First type to compare * @template U - Second type to compare * * @example * ```typescript * type Test1 = Equals; // true * type Test2 = Equals; // false * ``` */ export type Equals = (() => G extends T ? 1 : 2) extends () => G extends U ? 1 : 2 ? true : false; /** * Conditional type that resolves based on whether T is assignable to U * * @template T - The type to check * @template U - The type to check against * @template Then - Type to return if true * @template Else - Type to return if false */ export type If = T extends U ? Then : Else; /** * Check if a type is never * * @template T - The type to check */ export type IsNever = [T] extends [never] ? true : false; /** * Check if a type is unknown * * @template T - The type to check */ export type IsUnknown = unknown extends T ? (IsNever extends true ? false : true) : false; /** * Check if a type is any * * @template T - The type to check */ export type IsAny = 0 extends 1 & T ? true : false; /** * Exclude properties with never values * * @template T - The object type to filter */ export type ExcludeNever = { [K in keyof T as T[K] extends never ? never : K]: T[K]; }; /** * Merge two types, with the second type taking precedence * * @template T - Base type * @template U - Override type * * @example * ```typescript * type Base = { a: string; b: number }; * type Override = { b: string; c: boolean }; * type Merged = Merge; * // { a: string; b: string; c: boolean } * ``` */ export type Merge = Prettify & U>; /** * Create a type with only the shared keys between two types * * @template T - First type * @template U - Second type */ export type Intersection = Pick>; /** * Create a type with keys that exist in T but not in U * * @template T - Base type * @template U - Type to diff against */ export type Diff = Pick>; /** * Rename keys in an object type * * @template T - The object type * @template KeyMap - A mapping of old keys to new keys * * @example * ```typescript * type User = { firstName: string; lastName: string }; * type Renamed = RenameKeys; * // { first: string; last: string } * ``` */ export type RenameKeys> = { [K in keyof T as K extends keyof KeyMap ? KeyMap[K] : K]: T[K]; }; /** * Convert a string literal type to uppercase * * @template S - The string literal type */ export type UpperCase = Uppercase; /** * Convert a string literal type to lowercase * * @template S - The string literal type */ export type LowerCase = Lowercase; /** * Capitalize the first letter of a string literal type * * @template S - The string literal type */ export type CapitalizeString = Capitalize; /** * Uncapitalize the first letter of a string literal type * * @template S - The string literal type */ export type UncapitalizeString = Uncapitalize; /** * Split a string literal by a delimiter * * @template S - The string to split * @template D - The delimiter * * @example * ```typescript * type Parts = Split<'a/b/c', '/'>; // ['a', 'b', 'c'] * ``` */ export type Split = S extends `${infer Head}${D}${infer Tail}` ? [Head, ...Split] : [S]; /** * Join string literal types with a delimiter * * @template T - Array of string literals * @template D - The delimiter * * @example * ```typescript * type Joined = Join<['a', 'b', 'c'], '-'>; // 'a-b-c' * ``` */ export type Join = T extends readonly [] ? '' : T extends readonly [infer F extends string] ? F : T extends readonly [infer F extends string, ...infer R extends string[]] ? `${F}${D}${Join}` : never; /** * Get the first element type of a tuple * * @template T - A tuple type */ export type Head = T extends readonly [infer H, ...unknown[]] ? H : never; /** * Get all elements except the first from a tuple * * @template T - A tuple type */ export type Tail = T extends readonly [unknown, ...infer R] ? R : never; /** * Get the last element type of a tuple * * @template T - A tuple type */ export type Last = T extends readonly [...unknown[], infer L] ? L : never; /** * Get the length of a tuple type * * @template T - A tuple type */ export type Length = T['length']; /** * Prepend an element to a tuple type * * @template T - A tuple type * @template E - The element to prepend */ export type Prepend = [E, ...T]; /** * Append an element to a tuple type * * @template T - A tuple type * @template E - The element to append */ export type Append = [...T, E]; /** * Props type for a React component * * @template T - A React component type */ export type PropsOf> = T extends React.ComponentType ? P : never; /** * Children-only props */ export interface ChildrenProps { readonly children: React.ReactNode; } /** * Optional children props */ export interface OptionalChildrenProps { readonly children?: React.ReactNode; } /** * Class name prop */ export interface ClassNameProps { readonly className?: string; } /** * Style prop */ export interface StyleProps { readonly style?: React.CSSProperties; } /** * Common HTML element props */ export type HTMLProps = React.HTMLAttributes & ClassNameProps & StyleProps; /** * Polymorphic component props - supports "as" prop for element type * * @template E - The default element type * @template P - Additional props * * @example * ```typescript * type ButtonProps = PolymorphicProps<'button', { variant: 'primary' | 'secondary' }>; * // Supports: