A
arktype•2mo ago
ciscoheat

Testing a type in pipe

Congratulations on the 2.0 release, it's working great! 😀 Is it possible/best practice to run a type inside pipe? I'm having this test condition:
If string is a valid url, return URL
Else return null
If string is a valid url, return URL
Else return null
I'm not sure of the best way to handle this scenario with morphs? I see there's a second parameter for pipe.try, can it be used to simplify?
4 Replies
ciscoheat
ciscoheatOP•2mo ago
Here's the simple solution:
const nullUrl = type('string').pipe((s) => {
try {
return new URL(s);
} catch {
return null;
}
});
const nullUrl = type('string').pipe((s) => {
try {
return new URL(s);
} catch {
return null;
}
});
But can it be improved with morphs?
ssalbdivad
ssalbdivad•2mo ago
No but it could be simplified with pattern matching which we're about to release 😊 I mean under the hood, pattern matching is just an ordered union with morphs... but without the new syntax, creating an ordered union in 2.0.4 would probably be a bit confusing haha (you'd have to use the underlying @ark/schema representation)
ssalbdivad
ssalbdivad•2mo ago
At that point you will be able to do it like this:
No description
ciscoheat
ciscoheatOP•5w ago
Ok, looks very nice!

Did you find this page helpful?