A
arktype•5w ago
ciscoheat

Validate Record values with morphs

Is it possible to do more advanced validation on Records? Ideally I'd like to apply any morph to each item in a Record.
const nullNumber = type('number').pipe((s) => s ? Number(s) : null);

const obj = type({
searches: 'Record<string, ???>'
});
const nullNumber = type('number').pipe((s) => s ? Number(s) : null);

const obj = type({
searches: 'Record<string, ???>'
});
In the ??? place, I'd like to validate against nullNumber, is it possible?
6 Replies
TizzySaurus
TizzySaurus•5w ago
Have you tried using a scope? Something like
const { nullNumber, obj } = scope({
nullNumber: ["number", "=>", (s) => s ? Number(s) : null],
searches: "Record<string, nullNumber>",
}).export();
const { nullNumber, obj } = scope({
nullNumber: ["number", "=>", (s) => s ? Number(s) : null],
searches: "Record<string, nullNumber>",
}).export();
ssalbdivad
ssalbdivad•5w ago
Yeah a record is a Type like any other the value could be anything. In a case like this, you could create your record using type.Record("string", nullNumber)
ciscoheat
ciscoheatOP•5w ago
Ah, that's nice, I knew it was possible, just didn't know the syntax. 🙂
ssalbdivad
ssalbdivad•5w ago
Record is common so it is attached directly to type but all keywords are available under type.keywords, so you can invoke any generic from there
ciscoheat
ciscoheatOP•5w ago
Again, it's just amazing how flexible and convenient you've made this I'm gonna put Arktype to good use in an upcoming large project
ssalbdivad
ssalbdivad•5w ago
Thank you! It really helps that under the hood, all types work the same way so you can always compose them without worrying about what form is allowed where Even the output of the new match expression will be a union you can compose with any other Type!

Did you find this page helpful?