Default value for an invalid field of object #809
Replies: 1 comment 2 replies
-
Unfortunately we have "catch morphs" planned but not available yet (still need to add a description😅): For right now the best workaround would be to use a broad input type like const validSortBy = type(
"'index' | 'name' | 'level' | 'price' | null | undefined"
)
const validDirection = type("'asc' | 'desc' | null | undefined")
export const myType = type({
sortBy: morph("unknown", (value) =>
validSortBy.allows(value) ? value : null
),
orderBy: morph("unknown", (value) =>
validDirection.allows(value) ? value : null
)
}) You can mess around with the approach on StackBlitz here: https://stackblitz.com/edit/mrvfrm-ytjzwk?file=type.ts Note that the upcoming #763 would be separate, since for now it does not apply if the key is present but has a value of undefined, like TypeScript's const PersonArktype = morph(
{
name: "string"
},
(person) => ({ ...person, lengthOfName: person.name.length })
); |
Beta Was this translation helpful? Give feedback.
-
In
zod
there is a pattern to set initial value in caseundefined
and default value on errorExample:
If either
sortBy
ordirection
was invalid orundefined
, they will be set tonull
and not throw error on parse execution.This behavior really useful to parse URL queries since it prevents the URL queries getting crowded by empty field when value was undefined which makes the URL looks ugly.
Is there a way to achieve this in
arktype
?Beta Was this translation helpful? Give feedback.
All reactions