https://github.com/kossnocorp/ofcoerce
Lightweight type coercion library
https://github.com/kossnocorp/ofcoerce
Last synced: 24 days ago
JSON representation
Lightweight type coercion library
- Host: GitHub
- URL: https://github.com/kossnocorp/ofcoerce
- Owner: kossnocorp
- License: mit
- Created: 2024-05-27T07:10:41.000Z (11 months ago)
- Default Branch: main
- Last Pushed: 2025-02-21T02:40:15.000Z (2 months ago)
- Last Synced: 2025-03-26T19:45:58.316Z (about 1 month ago)
- Language: TypeScript
- Size: 126 KB
- Stars: 77
- Watchers: 1
- Forks: 2
- Open Issues: 3
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE.md
Awesome Lists containing this project
README
# Of Coerce!
Of Coerce! is a lightweight, near-zero overhead alternative to [Zod](https://zod.dev/) and [Valibot](https://valibot.dev/).
Unlike these libraries, Of Coerce! focuses on a single task: ensuring the data corresponds to the types.
It uses built-in JavaScript features to coerce whatever you pass to it, which makes it the fastest and the most lightweight solution (full library is `381B`!).
```ts
import { coercer } from "ofcoerce";interface User {
name: string;
email: string;
age?: number;
}const coerceUser = coercer(($) => ({
name: String,
email: String,
age: $.Optional(Number),
}));const user = coerceUser({ user: "Sasha", age: "37" });
//=> { user: "Sasha", email: "", age: 37 }
```It accepts the desired shape type as the generic argument and type-checks the defined schema against it.
But just like the alternatives, it allows inferring types from the schema:
```ts
import { coercer, FromCoercer } from "ofcoerce";const coerceUser = coercer.infer(($) => ({
name: String,
email: String,
age: $.Optional(Number),
}));type User = FromCoercer;
// { user: string, email: string, age?: number }
```It also accepts `FormData` making it ideal when working with forms, especially inside of React Server Components:
```tsx
import { coercer } from "ofcoerce";const coerceForm = coercer({
email: String,
password: String,
});function SignInForm() {
return (
{
"use server";
const form = coerceForm(formData);
await signIn(form);
}}
>
Sign in
);
}
```You can also use constructors as coercers, that is useful for example when working with `File`:
```tsx
import { coercer } from "ofcoerce";const coerceFile = coercer({
file: File,
});function UploadForm() {
return (
{
"use server";
const form = coerceFile(formData);
await upload(form);
}}
>
Upload
);
}
```It will check if the value is an instance of `File`, and if not, it will try to call `new File()` without parameters.
## Getting started
### Installation
Start by installing the package:
```sh
npm i ofcoerce
```## Changelog
See [the changelog](./CHANGELOG.md).
## License
[MIT © Sasha Koss](https://kossnocorp.mit-license.org/)