Can I create a regular Non-Nullable type with Optional if a default is provided? #732
-
In Zod, you can do things like The current TypeBox API doesn't seem to allow this, where Is there a way to do this? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
@divmgl Hi, You can override default type inference by wrapping a type in Unsafe and specifying the exact inference type you expect. The following type will represent optional property schematic (so const S = Type.Unsafe<string>(
Type.Optional(Type.String({ default: "hello" }))
)
If this is something you need to do for a lot of properties, you can create a generic function to handle this in a consistent way (which is recommended as it can make refactoring rules around optional handling simpler) import { Type, Static, TSchema } from '@sinclair/typebox'
// Specialized Optional
export function FormOptional<T extends TSchema>(schema: T) {
return Type.Unsafe<Static<T>>(Type.Optional(schema))
}
const T = Type.Object({
hello: FormOptional(Type.String({ default: 'hello' })),
world: FormOptional(Type.String({ default: 'world' }))
}) Hope this helps |
Beta Was this translation helpful? Give feedback.
@divmgl Hi,
You can override default type inference by wrapping a type in Unsafe and specifying the exact inference type you expect. The following type will represent optional property schematic (so
string | undefined
) but will infer asstring
only.If this is so…