Default value for an invalid field of object #809
Replies: 2 comments 4 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.
-
It looks like you can do this with const page = type("number>1").default(1) or am I missing something? or is this the right way? export const ThemeSchema = type({
'name': '"light" | "dark" | "system" = "system"'
}); btw @ssalbdivad I couldn't find this in the docs, does that mean this is not the right way to achieve this? |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
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