Cast empty string in place for literal as default value

Hi, I'm trying to use an array of string literals for a select field using Superforms. However, I would like to have the default value be an empty string, so that the default select field is not selected. I've tried the following, but this doesn't seem to work
const RETURN_TYPES = ['Exit'] as const;
type ReturnType = typeof RETURN_TYPES[number];
export const formReturnSchema = type({
returnType: type.enumerated(...RETURN_TYPES).default('' as type.cast<ReturnType>),
});
const RETURN_TYPES = ['Exit'] as const;
type ReturnType = typeof RETURN_TYPES[number];
export const formReturnSchema = type({
returnType: type.enumerated(...RETURN_TYPES).default('' as type.cast<ReturnType>),
});
This gives me a runtime error saying Default must be 'Exit'
2 Replies
ssalbdivad
ssalbdivad4w ago
Hi! So the problem here is that a default value has to be assignable to the underlying property type. It seems like you'd want to use a different construct if you have default values like "" that aren't actually valid if the form was submitted. Is there a way to specify the default values separately? If there's some other mechanism for it in superforms rather than extracting it from the schema itself, there could be a utility function that could extract that default object with empty string automatically from a Type.
kyoumei
kyoumeiOP4w ago
Thanks for pointing me in the right direction for this! I've managed to get this working by instead of using Arktype's default method when creating the schema, I am passing in default values via Superforms when initializing the form.
function useEmptyStringAsFiller<T extends readonly string[]>(): T[number] {
return '' as T[number];
}
function useEmptyStringAsFiller<T extends readonly string[]>(): T[number] {
return '' as T[number];
}
My form declaration (in server load func):
const form = await superValidate(
arktype(formReturnSchema, {
defaults: {
returnType: useEmptyStringAsFiller<typeof RETURN_TYPES>(),
}
})
)
const form = await superValidate(
arktype(formReturnSchema, {
defaults: {
returnType: useEmptyStringAsFiller<typeof RETURN_TYPES>(),
}
})
)

Did you find this page helpful?