Comments (12)
Example to check if parsed data satisfies an existing type using the satisfies
keyword, this will work for all kind of errors:
import { email, minLength, object, parse, string } from "valibot";
type LoginInput = {
email: string;
password: string;
};
const LoginSchema = object({
email: string([email()]),
password: string([minLength(8)]),
});
const LoginErrorSchema = object({
email: string([email()]),
});
let input = parse(LoginSchema, {}) satisfies LoginInput; // OK
let inputError = parse(LoginErrorSchema, {}) satisfies LoginInput; // ERROR: Property 'password' is missing in type '{ email: string; }' but required in type 'LoginInput'.
I've tried to create a helper type to use the satisfies keyword with a ObjectSchema type, but quickly had to go to complex typing and there would be tons of edge cases. This monster of a type would probably be out of scope for a simple library like this one.
My current recommendation would be to use the satisfies
keyword on parsed data, since the satisfies
keyword was made for this kind of validation. At least until there is a simple way to use, satisfies with ObjectSchema type!
Hope this helps someone!
from valibot.
I haven't had any use for it yet, but understand why it can be useful. Thank you creating this issue.
from valibot.
This is possible with BaseSchema
:
import * as v from 'valibot';
type Login = {
email: string;
password: string
};
export const Login = v.object({
email: v.string(),
password: v.string(),
}) satisfies v.BaseSchema<Login>;
from valibot.
Thank you very much! I understand the use case and can see why this is useful. I will have a look at how other schema libraries solve this in the next few weeks.
from valibot.
Thank you @Arthie for all the info!
from valibot.
@fabian-hiller Amazing, thanks!
Just to confirm, does this show an error in both of the cases below?
- Extra property in Valibot schema
import * as v from 'valibot';
type Login = {
email: string;
password: string
};
export const Player = v.object({
email: v.string(),
password: v.string(),
x: v.string(), // 💥 Error expected here (extra `x` property)
}) satisfies v.BaseSchema<Login>;
- Missing property in Valibot schema
import * as v from 'valibot';
type Login = {
email: string;
password: string
};
export const Player = v.object({
email: v.string(),
// 💥 Error expected here (missing `password` property)
}) satisfies v.BaseSchema<Login>;
from valibot.
The second works, but the first does not. The reason is that satisfies
only checks the input and output type, but not the structure of the object definition.
You can also convert TypeScript types to a Valibot schema on this website: https://sinclairzx81.github.io/typebox-workbench/
from valibot.
Ok, for this feature, the first one would also need to be an error to prevent excess properties being passed. This would be important if eg. adding the validated object to a database - would be problematic if inconsistent with the type.
Would you consider reopening the issue and adding a feature to allow the first too? Eg. via a type annotation?
from valibot.
I have no idea how to implement such a feature. Feel free to research it and share a proof of concept with me.
from valibot.
Hm... maybe the generic type parameter could be passed into the v.object()
schema method, similar to the approach in the exact object blog post by @ddprrt
https://fettblog.eu/typescript-match-the-exact-object-shape/
from valibot.
This would require a breaking change and more cumbersome code in many cases. Can you explain why such a feature would be useful? Shouldn't the Valibot schema be the source of truth for type and validation?
from valibot.
Shouldn't the Valibot schema be the source of truth for type and validation?
I think that for some applications, the source of truth is closer to where the data lives (eg. the database), not the validation layer with the user, which in many cases is an incomplete representation of the data model.
We have our source of truth as types in our database files, where SafeQL type-checks them against the SQL queries we write.
from valibot.
Related Issues (20)
- The forwardAsync method is not available HOT 3
- 0.28.0 bug: when inside union, transform is not returning the transformed result HOT 2
- Avoid barrel files and create distinct files for exports HOT 6
- Best way for validation optional strings HOT 11
- Docs: Add ctrl + k hotkey for search to enable searching on windows (cmd is reserved) HOT 10
- Method of modifying input type to account for acceptable invalid inputs HOT 5
- Transformation action now executes after failed schema check HOT 41
- [i18n] Add Dutch HOT 5
- Enable `v.recursive()` getter to accept a `value` to improving usage flexibility HOT 10
- Schema with interpolated value fails HOT 5
- [docs] Command + K doesn't prevent default, opening the URL bar in Firefox HOT 2
- Tree shaking is not performed on `RegExp` in Webpack HOT 4
- Custom validator: what to put in expect and actionIssue arguments HOT 2
- Add possibility to convert entries to input types if possible HOT 1
- Nullable form field with constraints HOT 4
- flatten return type/FlatErrors type is incorrect for object schemas that contain properties with async schemas HOT 4
- Request for Enhancement: Support for Multiple Keys in variant Function HOT 3
- Derived Schema Validations? HOT 1
- Partial variant schema HOT 1
- Can't get `instance` to work HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from valibot.