-
-
Notifications
You must be signed in to change notification settings - Fork 218
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
feat: flavored types #950
base: main
Are you sure you want to change the base?
feat: flavored types #950
Conversation
Thank you for creating this PR. Can you explain the pros and cons of |
I'm not aware of other validation libraries using flavored types in addition to branded ones, but there's a database schema library called kanel that makes use of them. The purpose there is to avoid mixing up ids of different entities, but not require the use of a validation library or custom functions for casting new ids to be used as arguments. I prefer using flavored types for ids and ISO timestamps because all the existing values are more or less guaranteed to be flavored from either validated API inputs or database queries. There's a loss in ergonomics for no or very little extra safety when branded types force me to implement wrapped functions a la tl;dr - flavored types don't get in my way, but will stop me from mixing up validated data (and all my data is validated.) In critical places I use runtime assertions and/or branded types. |
Is the only difference that the |
That's right. |
Am I understanding correctly that an unflavored type can be passed on to a flavored type and that's the difference too type A = string & { foo?: 'A' };
type B = string & { foo?: 'B' };
function createA(): A {
return 'hello';
}
const test1: A = createA(); // This works
const test2: A = 'hello'; // This works (but would not work with `brand`)
const test3: string = createA(); // This works
const test4: B = createA(); // But this does not work |
Yes, I added similar examples to the docs here. In essence:
|
In general, I like the idea of a |
Maybe |
Here is a list of names with
And here is a list of completely new and independent names:
What's your favorite so far? |
I like |
I am not sure we should use the same symbol. This could cause problems when people extend existing schemas that end up using both actions. Let me think about the name a bit more. I'm not sure what's best yet. |
I'm not sure about that. Having interop and having the ability to easily make schemas more or less strict sounds useful and convenient. Extending schemas is explicit and messing up the type by (re)branding or (re)flavoring it (possibly with a different name) would possible no matter what the feature is called or the symbol used. |
Thanks for your feedback. I will have to investigate this before moving forward. I may prioritize our v1 RC first before doing this. |
f41426c
to
d713dfe
Compare
Less strict version of
brand
. The code is basically the same, just a couple of more test cases.