You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I read through #453 but haven't found an answer to the following questions regarding branded types or what the recommendation is for handling branded types. It reads to use refine or parse but I haven't understood how.
Branded primitives
Consider a string that matches a regex pattern should be branded. Is the following correct? It does work but I wonder if there is a recommended / better approach
import*asCODfrom"io-ts/Codec";import*asDECfrom"io-ts/Decoder";import*asENCfrom"io-ts/Encoder";import*asEfrom"fp-ts/Either"constfromPredicate=<A>(predicate: (i: unknown)=>i is A,message: string)=>(i: unknown)=>E.fromPredicate(predicate,()=>DEC.error(i,message))(i);interfaceDocumentCodeBrand{readonlyDocumentCode: unique symbol;}typeDocumentCode=string&DocumentCodeBrand;constPATTERN=/^[A-Z]\d[A-Z]\d$/;constis=(i: unknown): i is DocumentCode=>typeofi==="string"&&PATTERN.test(i);constEncoder: ENC.Encoder<string,DocumentCode>={encode: String};constDecoder: DEC.Decoder<unknown,DocumentCode>={decode: CAT.fromPredicate(is,`DocumentCode must be a string of format ${String(PATTERN)}`),};constCodec: COD.Codec<unknown,string,DocumentCode>=COD.make(Decoder,Encoder);
Branded structures
Consider this codec and the corresponding type. How can you achieve a branded struct?
I think this is correct. It is pretty much how it is implemented in this experimental branch gcanti/io-ts-types#127. You can use Guard to reduce code a bit (look at the implementation of UUID for example). I published some of the code in this branch as https://github.com/tchak/io-ts-types-experimental (npm install io-ts-types-experimental).
📖 Documentation
I read through #453 but haven't found an answer to the following questions regarding branded types or what the recommendation is for handling branded types. It reads to use refine or parse but I haven't understood how.
Branded primitives
Consider a string that matches a regex pattern should be branded. Is the following correct? It does work but I wonder if there is a recommended / better approach
Branded structures
Consider this codec and the corresponding type. How can you achieve a branded struct?
The text was updated successfully, but these errors were encountered: