An open API service indexing awesome lists of open source software.

https://github.com/saqqdy/uni-types

Universal TypeScript type utilities - A comprehensive collection of type helpers for TypeScript development
https://github.com/saqqdy/uni-types

deep-partial deep-required omit partial pick required type-helpers type-utilities types typescript utility-types

Last synced: about 1 month ago
JSON representation

Universal TypeScript type utilities - A comprehensive collection of type helpers for TypeScript development

Awesome Lists containing this project

README

          

# uni-types

**Universal TypeScript Type Utilities**

A comprehensive collection of type helpers for TypeScript development

[![NPM version][npm-image]][npm-url]
[![NPM downloads][download-image]][download-url]
![TypeScript][typescript-url]
[![Codecov][codecov-image]][codecov-url]
[![License][license-image]][license-url]

[**Documentation**](https://saqqdy.github.io/uni-types/) · [**中文文档**](./README_CN.md)

## Features

- 🎯 **800+ Type Utilities** - Comprehensive type helpers for every use case
- 🔒 **Type Safe** - Full TypeScript support with strict type checking
- 📦 **Zero Dependencies** - Lightweight and tree-shakeable
- 🚀 **TypeScript 5.x** - Built with the latest TypeScript features
- 🌍 **Bilingual Docs** - Documentation in English and Chinese

## Installation

```bash
# pnpm
pnpm add uni-types

# yarn
yarn add uni-types

# npm
npm install uni-types
```

## Quick Start

```typescript
import type {
PickRequired,
DeepPartial,
IsArray,
Brand,
If,
Paths
} from 'uni-types'

// Core: Make specific properties required
interface User {
name?: string
age?: number
email: string
}

type RequiredUser = PickRequired
// { name: string; age: number; email: string }

// Deep: Make all nested properties optional
interface Config {
database: {
host: string
port: number
}
}

type PartialConfig = DeepPartial
// { database?: { host?: string; port?: number } }

// Brand: Create nominal types
type UserId = Brand
type OrderId = Brand
// UserId and OrderId are not interchangeable!

// Conditional: Type-level logic
type Result = If // 'success'
```

## API Reference

### Core Operations

| Type | Description |
|------|-------------|
| `PickRequired` | Make specified properties required |
| `OmitRequired` | Make properties except specified ones required |
| `PickPartial` | Make specified properties optional |
| `OmitPartial` | Make properties except specified ones optional |

### Tuple Operations

| Type | Description |
|------|-------------|
| `Head` | Get first element of tuple |
| `Last` | Get last element of tuple |
| `Tail` | Get all elements except first |
| `Init` | Get all elements except last |
| `Reverse` | Reverse a tuple |
| `Flatten` | Flatten nested tuples |
| `TupleLength` | Get tuple length |
| `IsEmptyTuple` | Check if tuple is empty |

### Deep Operations

| Type | Description |
|------|-------------|
| `DeepPartial` | Make all nested properties optional |
| `DeepRequired` | Make all nested properties required |
| `DeepReadonly` | Make all nested properties readonly |
| `DeepMutable` | Make all nested properties mutable |
| `DeepOmit` | Omit properties by path |
| `DeepPick` | Pick properties by path |

### Type Guards

| Type | Description |
|------|-------------|
| `IsArray` | Check if type is an array |
| `IsTuple` | Check if type is a tuple |
| `IsEqual` | Check if two types are equal |
| `IsAny` | Check if type is `any` |
| `IsNever` | Check if type is `never` |
| `IsUnknown` | Check if type is `unknown` |
| `IsFunction` | Check if type is a function |
| `IsAsyncFunction` | Check if type is an async function |

### Conditional Types *(v1.1.0)*

| Type | Description |
|------|-------------|
| `If` | Type-level if-then-else |
| `Not` | Logical NOT for boolean types |
| `And` | Logical AND for boolean types |
| `Or
` | Logical OR for boolean types |
| `Assert` | Type constraint assertion |

### Brand Types *(v1.1.0)*

| Type | Description |
|------|-------------|
| `Brand` | Create a branded type for nominal typing |
| `Unbrand` | Extract underlying type from branded type |

### Function Utilities *(v1.1.0)*

| Type | Description |
|------|-------------|
| `Parameters` | Get function parameters as tuple |
| `ReturnType` | Get function return type |
| `NthParameter` | Get Nth parameter type |
| `AsyncReturnType` | Extract async function return type |
| `ThisParameterType` | Get `this` parameter type |
| `OmitThisParameter` | Omit `this` parameter from function |

### Template Literal Utilities *(v1.1.0)*

| Type | Description |
|------|-------------|
| `ReplaceAll` | Replace all occurrences |
| `Replace` | Replace first occurrence |
| `Trim` | Trim whitespace |
| `StringToArray` | Convert string to array |
| `CapitalizeAll` | Capitalize all words |
| `StartsWith` | Check if string starts with prefix |
| `EndsWith` | Check if string ends with suffix |
| `StringLength` | Get string length |

### Numeric Utilities *(v1.1.0)*

| Type | Description |
|------|-------------|
| `Inc` | Increment number |
| `Dec` | Decrement number |
| `Add
` | Add two numbers |
| `Subtract
` | Subtract two numbers |
| `GreaterThan
` | Check if A > B |
| `LessThan
` | Check if A < B |
| `Max
` | Maximum of two numbers |
| `Min
` | Minimum of two numbers |

### Path Types

| Type | Description |
|------|-------------|
| `Paths` | Get all nested property paths |
| `PathValue` | Get value type at path |
| `ValidPath` | Check if path is valid |
| `ArrayPaths` | Get paths including array indices |
| `LeafPaths` | Get paths to primitive values |

### Key Utilities *(v1.1.0)*

| Type | Description |
|------|-------------|
| `Keys` | Get all keys |
| `RenameKeys` | Rename keys based on mapping |
| `PrefixKeys` | Add prefix to all keys |
| `SuffixKeys` | Add suffix to all keys |
| `KeysByValueType` | Get keys by value type |

### Record Utilities *(v1.1.0)*

| Type | Description |
|------|-------------|
| `DeepNullable` | Make all properties nullable |
| `DeepOptional` | Make all properties optional |
| `Immutable` | Make all properties readonly |
| `Mutable` | Make all properties mutable |
| `DeepNonNullable` | Remove null/undefined from all properties |
| `Exact` | Ensure exact shape match |

### Schema Validation *(v1.2.0)*

| Type | Description |
|------|-------------|
| `RuntimeGuard` | Define type guard function for runtime checking |
| `GuardedType` | Extract type from type guard function |
| `HasRuntimeCheck` | Check if type has runtime check available |
| `ZodOutput` | Extract output type from Zod schema |
| `ZodInput` | Extract input type from Zod schema |
| `ZodShape` | Extract shape from ZodObject schema |
| `ZodRequiredKeys` | Get required keys from Zod schema |
| `ZodOptionalKeys` | Get optional keys from Zod schema |
| `YupOutput` | Extract output type from Yup schema |
| `YupInput` | Extract input type from Yup schema |

### Ecosystem Integration *(v1.2.0)*

| Type | Description |
|------|-------------|
| `ComponentProps` | Extract props from React component |
| `PropsWithChildren

` | Add children to props type |
| `RequiredProps


` | Get required prop keys |
| `OptionalProps


` | Get optional prop keys |
| `VuePropType` | Vue prop type definition |
| `VueEmitType` | Vue emit function type |
| `PrismaCreateInput` | Create input type for Prisma models |
| `PrismaUpdateInput` | Update input type for Prisma models |
| `PrismaWhereInput` | Where input type for Prisma queries |
| `TRPCProcedureInput` | Extract input from tRPC procedure |
| `TRPCProcedureOutput` | Extract output from tRPC procedure |

### Performance Optimization *(v1.2.0)*

| Type | Description |
|------|-------------|
| `Simplify` | Flatten intersection types |
| `DeepSimplify` | Recursively simplify nested types |
| `Compact` | Remove never and undefined properties |
| `StripNever` | Remove never properties |
| `StripUndefined` | Remove undefined properties |
| `MergeAll` | Merge multiple object types |
| `Lazy` | Defer type evaluation |
| `Cached` | Cache type computation |
| `Memoized` | Memoize type computation |

### Advanced Type Patterns *(v1.3.0)*

| Type | Description |
|------|-------------|
| `Match` | Type-level pattern matching |
| `Recurse` | Type-level recursion with depth limit |
| `Depth` | Get maximum depth of nested type |
| `TypeFilter` | Filter tuple by predicate |
| `TypeFind` | Find first matching element |
| `TypeIncludes` | Check if tuple includes element |
| `TypeEvery` | Check if all elements match |
| `TypeSome` | Check if any element matches |

### Type-Level Collections *(v1.3.0)*

| Type | Description |
|------|-------------|
| `TypeSet` | Type-level Set representation |
| `SetAdd` | Add element to type set |
| `SetRemove` | Remove element from type set |
| `SetUnion
` | Union of two type sets |
| `SetIntersection
` | Intersection of two type sets |
| `SetDifference
` | Difference of two type sets |
| `TypeMap` | Type-level Map representation |
| `MapGet` | Get value from type map |
| `MapSet` | Set value in type map |
| `ListFilter` | Filter list elements |
| `ListReverse` | Reverse a list |
| `ListConcat
` | Concatenate two lists |
| `ListTake` | Take first N elements |
| `ListChunk` | Chunk list into sublists |

### Type Assertions & Constraints *(v1.3.0)*

| Type | Description |
|------|-------------|
| `AssertEqual` | Assert types are equal |
| `AssertExtends` | Assert T extends U |
| `RequireKeys` | Require specific keys |
| `RequireAtLeastOne` | Require at least one key |
| `RequireExactlyOne` | Require exactly one key |
| `RequireAllOrNone` | Require all or none keys |
| `HasProperty` | Ensure object has property |
| `RequireArray` | Ensure type is array |
| `RequireFunction` | Ensure type is function |

### String Operations *(v1.3.0)*

| Type | Description |
|------|-------------|
| `Split` | Split string by delimiter |
| `Join` | Join string array with separator |
| `KebabCase` | Convert to kebab-case |
| `PascalCase` | Convert to PascalCase |
| `ConstantCase` | Convert to CONSTANT_CASE |
| `IsEmail` | Check if string is email |
| `IsUUID` | Check if string is UUID |
| `IsURL` | Check if string is URL |
| `ReverseString` | Reverse a string |

### Promise & Async Utilities *(v1.3.0)*

| Type | Description |
|------|-------------|
| `PromiseValue` | Extract value from Promise (deep) |
| `IsPromise` | Check if type is Promise |
| `UnwrapPromise` | Unwrap or return original |
| `AsyncReturnType` | Return type of async function |
| `MakeAsync` | Make function async |
| `PromiseAll` | Await all promises |
| `AsyncResult` | Rust-style Result type |
| `Deferred` | Deferred promise type |

### Object Operations *(v1.3.0)*

| Type | Description |
|------|-------------|
| `ObjectMap` | Map over object values |
| `ObjectFilter` | Filter object properties |
| `ObjectPickByType` | Pick by value type |
| `ObjectInvert` | Invert object (swap keys/values) |
| `DeepMerge
` | Deep merge objects |
| `ObjectPath` | Get value at path |
| `PathExists` | Check if path exists |
| `KeysOfType` | Get keys of specific type |

### JSON Schema *(v1.3.0)*

| Type | Description |
|------|-------------|
| `JsonSchemaType` | Map TS types to JSON Schema types |
| `JsonSchema` | Full JSON Schema type |
| `OpenAPISchema` | OpenAPI 3.0 Schema |
| `OpenAPIResponse` | OpenAPI Response |
| `OpenAPIRequestBody` | OpenAPI Request Body |
| `OpenAPIParameter` | OpenAPI Parameter |
| `OpenAPIDocument` | OpenAPI Document |

### Extended Ecosystem *(v1.3.0)*

| Type | Description |
|------|-------------|
| `NextPageProps` | Next.js page props |
| `ServerComponentProps` | Next.js server component props |
| `NuxtPageMeta` | Nuxt page meta |
| `NuxtComposable` | Nuxt composable type |
| `SolidSignal` | SolidJS signal type |
| `SolidResource` | SolidJS resource type |
| `SvelteStore` | Svelte store type |
| `SvelteAction` | Svelte action type |

### Type-Level Algorithms *(v1.4.0)*

| Type | Description |
|------|-------------|
| `Sort` | Sort tuple of numbers |
| `QuickSort` | QuickSort implementation |
| `MergeSort` | MergeSort implementation |
| `Find` | Find first matching element |
| `FindIndex` | Find index of matching element |
| `Includes` | Check if tuple includes element |
| `IndexOf` | Get index of element |
| `GCD
` | Greatest Common Divisor |
| `LCM
` | Least Common Multiple |
| `Factorial` | Factorial of number |
| `Fibonacci` | Fibonacci number |
| `IsPrime` | Check if number is prime |
| `LongestCommonPrefix` | Longest common prefix of strings |
| `LevenshteinDistance
` | Edit distance between strings |
| `Reverse` | Reverse a tuple |
| `Unique` | Remove duplicates from tuple |
| `Flatten` | Flatten nested tuples |

### Type-Level Parsers *(v1.4.0)*

| Type | Description |
|------|-------------|
| `ParseJSON` | Parse JSON string to type |
| `StringifyJSON` | Stringify type to JSON |
| `IsValidJSON` | Check if string is valid JSON |
| `ParseURL` | Parse URL string |
| `QueryParams` | Parse query string |
| `PathParams` | Extract path params |
| `ParseCSV` | Parse CSV string |
| `StringifyCSV` | Stringify records to CSV |
| `ParseExpression` | Parse arithmetic expression |
| `EvaluateExpression` | Evaluate parsed expression |

### Type-Level State Machines *(v1.4.0)*

| Type | Description |
|------|-------------|
| `StateMachine` | State machine definition |
| `State` | State definition |
| `Transition` | Transition definition |
| `CurrentState` | Get current state |
| `NextState` | Get next state after event |
| `ValidTransitions` | Get valid transitions |
| `StateHistory` | State history type |
| `CanTransition` | Check if transition is valid |
| `IsTerminal` | Check if state is terminal |

### Type-Level Data Structures *(v1.4.0)*

| Type | Description |
|------|-------------|
| `Tree` | Tree type |
| `TreeNode` | Tree node type |
| `TreePath` | Path to value in tree |
| `TreeDepth` | Maximum depth of tree |
| `TreeLeaves` | All leaf values |
| `TreeFlatten` | Flatten tree to array |
| `Graph` | Graph type (adjacency list) |
| `GraphNode` | Graph node type |
| `GraphEdge` | Graph edge type |
| `GraphPath
` | Path between nodes |
| `GraphHasCycle
` | Check for cycles |
| `LinkedList` | Linked list type |
| `ListNode` | List node type |
| `ListHead` | Head of list |
| `ListTail` | Tail of list |
| `Stack` | Stack type (LIFO) |
| `Queue` | Queue type (FIFO) |
| `Push` | Push onto stack |
| `Pop` | Pop from stack |

### Type-Level HTTP & API *(v1.4.0)*

| Type | Description |
|------|-------------|
| `HTTPMethod` | HTTP methods |
| `HTTPStatus` | HTTP status codes |
| `HTTPHeaders` | HTTP headers type |
| `Route

` | Route definition |
| `RouteParams


` | Extract route params |
| `RouteQuery` | Route query type |
| `Router` | Router type |
| `APIEndpoint` | API endpoint type |
| `APIRequest` | API request type |
| `APIResponse` | API response type |
| `APIError` | API error type |
| `Middleware` | Middleware type |
| `Context` | Request context |
| `ComposeMiddleware` | Compose middleware chain |

### Type-Level Database *(v1.4.0)*

| Type | Description |
|------|-------------|
| `SQLType` | TypeScript to SQL type mapping |
| `CreateTable` | CREATE TABLE type |
| `SelectQuery` | SELECT query type |
| `WhereClause` | WHERE clause type |
| `JoinQuery` | JOIN query type |
| `Migration` | Migration type |
| `MigrationUp` | Up migration |
| `MigrationDown` | Down migration |
| `QueryBuilder` | Query builder type |
| `WhereBuilder` | WHERE builder type |
| `Index` | Index type |
| `UniqueIndex` | Unique index type |
| `CompositeIndex` | Composite index type |

### Type-Level Concurrency *(v1.4.0)*

| Type | Description |
|------|-------------|
| `Task` | Task type |
| `TaskResult` | Task result type |
| `TaskError` | Task error type |
| `TaskStatus` | Task status type |
| `Pipeline` | Pipeline type |
| `PipelineStage` | Pipeline stage type |
| `Scheduler` | Scheduler type |
| `Worker` | Worker type |
| `WorkerPool` | Worker pool type |
| `RateLimiter` | Rate limiter type |
| `Throttle` | Throttle type |
| `Debounce` | Debounce type |

### Type-Level Interop *(v1.4.0)*

| Type | Description |
|------|-------------|
| `ToTypeFest