@crbroughton/ts-utils
v0.2.3
Published
A collection of helper functions and types
Downloads
308
Maintainers
Readme
ts-utils
A collection of helper functions and types. To use any of the following, simply import into your project like so:
import { handleError, safeAwait } from '@crbroughton/ts-utils'
Installation
To install ts-utils
with Bun, run the following command:
bun i -D @crbroughton/ts-utils
await
The await
directory contains the following:
safeAwait
- This function return either a result or error value. This suppports both a Go and Rust like syntax, using overload functions.handleError
- To be used in conjunction withsafeAwait
.
The goal of the await
helpers is to make it more obvious where throw exceptions
occur and to help guide the user to write exception handlers. Please inspect the the accompanying example file file to see both helpers in action.
enum
The enum
directory contains the following:
EnumLike
- A helper type to define enum-like objectscreateEnum
- A function to create enum-like object
It is intended that you'll only need to interface with the createEnum
function,
however the EnumLike
type has been exported if you find yourself requiring it.
utils
The utils
directory for now only contains the Prettify
type, which will
improve your experience when hovering over type to get their underlying type
information.
Zod
The Zod directly currently contains only a single function, the zodObjectBuilder
function, which is
a helper to generate objects from a Zod object schema.
Use this function for whenever you need to generate
objects but don't want to see the entire object in
your code. This function support both full and partial
schema support. Below is an example of zodObjectBuilder
in action with it's various
use-cases.
* // Define a schema
* const UserSchema = z.object({
* id: z.string(),
* name: z.string(),
* settings: z.object({
* theme: z.enum(['light', 'dark']),
* notifications: z.boolean()
* })
* });
*
* // Create a single object with overrides
* const user = zodObjectBuilder({
* schema: UserSchema,
* overrides: { name: 'John', settings: { theme: 'dark' } }
* });
*
* // Create multiple objects with overrides
* const users = zodObjectBuilder({
* schema: UserSchema,
* overrides: [
* { name: 'John' },
* { name: 'Jane', settings: { theme: 'light' } }
* ]
* });
*
* // Create default object(nested in an array) with no overrides
* const defaultUsers = zodObjectBuilder({
* schema: UserSchema
* });
*
* // Preserve nested defaults with overrides
* const userWithDefaults = zodObjectBuilder({
* schema: UserSchema,
* overrides: { name: 'John', settings: { theme: 'dark' } },
* config: { preserveNestedDefaults: true }
* });
Development Installation
bun install
To run:
bun run index.ts
This project was created using bun init
in bun v1.1.27. Bun is a fast all-in-one JavaScript runtime.