top | item 46072333

(no title)

robertlagrant | 3 months ago

I keep wondering about a type system where you can say something like "A number greater than 4" or "A string of length greater than 0" or "A number greater than the value of $othernum". If you could do that, you could push so much of this "coping" logic to only the very edge of your application that validates inputs, and then proceed with lovely typesafe values.

discuss

order

epolanski|3 months ago

You can do it in typescript with branded types:

https://effect.website/docs/schema/advanced-usage/#branded-t...

There is some ceremony around it, but when you do the basic plumbing it's invaluable to import NonEmptyString100 schema to define a string between 1 and 100 chars, and have parsing and error handling for free anywhere, from your APIs to your forms.

This also implies that you cannot pass any string to an API expecting NonEmptyString100, it has to be that exact thing.

Or in e-commerce where we have complex pricing formulas (items like showers that need to be custom built for the customer) need to be configured and priced with some very complex formulas, often market dependent, and types just sing and avoid you multiplying a generic number (which will need to be a positive € schema) with a swiss VAT rate or to do really any operation if the API requires the branded version.

Typescript is an incredibly powerful language, it is kinda limited by its verbose syntax and JS compatibility but the things that you can express in Typescript I haven't seen in any other language.

marcelr|3 months ago

while this is nice, the type itself doesn't encode the logic (unlike refinement type)

i think this would be really nice if validation libraries like zod returned branded types when they are validating non-comp-time types (like z.ipv4() should return some IPv4 branded type)

davidmurdoch|3 months ago

Your can do that now in Typescript. But it will take several minutes to resolve your types. I've done it and it's a horrible dev experience, sadly.