Skip to content

Can I create a regular Non-Nullable type with Optional if a default is provided? #732

Answered by sinclairzx81
divmgl asked this question in Q&A
Discussion options

You must be logged in to vote

@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 as string only.

const S = Type.Unsafe<string>(
  Type.Optional(Type.String({ default: "hello" }))
)

Note that TypeBox considers the above unsafe as the schema and static type are non-equivalent (or more accurately, the static type is not directly derived from the schematic). However this may be permissible if there's an expectation that something (react-hook-form in this case) is always going to generate a property with the default annotation.

If this is so…

Replies: 1 comment 4 replies

Comment options

You must be logged in to vote
4 replies
@divmgl
Comment options

@sinclairzx81
Comment options

@divmgl
Comment options

@andrewdoro
Comment options

Answer selected by divmgl
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants