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)
The type encodes the logic in the schema, it is absolutely a refinement as every parser is. Maybe you meant a comparison with dependent types?
Now every time you will have to use a NonEmptyString255 as a type it has to be branded by passing through the constructor, so you can't pass a normal string to an API expecting it, and you get the error at type level. The logic is encoded in the schema itself, which you can click.
And it also provided the decoder (parser) and encoder (constructor). So you use the parser in a form or whatever and get parsing and precise errors (for it being too long, too short, not a string). And you can annotate the errors in any language you want too (German, Spanish, etc, English is the default)
Essentially this approach is similar to using some class NonEmptyString without using a class and while keeping the information at type level.
It's practical and the ceremony goes as far as copy pasting or providing a different refinement, besides, AI can write those with ease and you don't need to do it frequently, but it's nice in many places not mixing UserIDs with ProductID or any other string makes codebases much easier to follow and provides lots of invariants.
there’s problem with branded types this way now that i think of it
string
type nonEmptyStr = string & NonEmpty
type ipv4Str = string & IPv4
it’s not obvious how you’d automatically determine ipv4Str is also a nonEmptyStr, since the types themselves are just labels, they don’t store the refinements at type level
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)