-
Notifications
You must be signed in to change notification settings - Fork 18
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[Feature] plugins to enhance type validation #34
Comments
It's possible already! Something like this should work:
To make it generally available, you could import the object |
Excellent, thanks a lot! This works great. Just to document what I did... I separated types that need custom checking from other types into their own file. In our build process, we are not invoking ts-interface-builder for this file.
Other types with interfaces etc. that just require regular checks:
Now to consume it:
|
Hi @dsagal , I have a follow up question. I'm wondering if there is a way create a checker for a more complex type that invokes other checkers. For example, for type MyObjectList below I would like to verify that all the id values are unique. interface IMyObject {
id: string;
// other properties...
}
type MyObjectList = IMyObject[]; Thanks! |
Ok... I think I figured it out. Let me know if the code below looks about right... class TMyObjectList extends t.TType {
public getChecker(suite: t.ITypeSuite, strict: boolean): CheckerFunc {
const ttype = _TI.TMyObjectList;
const itemChecker = ttype.getChecker(suite, strict);
return (value: any, ctx: IContext) => {
const ok = itemChecker(value, ctx);
if (!ok) return ctx.fail(null, null, 1);
const ids = value.map((x: { id: string }) => x.id);
const hasDuplicates = new Set(ids).size !== ids.length;
if (hasDuplicates) return ctx.fail(null, "has duplicates", 0);
return true;
};
}
} |
Yup, this looks like it should work! |
Thanks for this awesome library! It is very well thought out.
It would be great if it could provide support to inject additional logic to validate certain types.
For example, given the type below:
I would like to add logic that verifies that the value is a valid date formatted as "YYYY-MM-DD".
I can see many other scenarios where similar validations would be useful. For example, for certain numbers you may want to verify that they are within a specific range (e.g. a "Percent" type would need to be between 0 and 100). Certain string types may need to be checked for length. An Email or PhoneType could be checked with a RegEx... etc.
The text was updated successfully, but these errors were encountered: