Skip to content

Optional passing for null? #759

Answered by sinclairzx81
m1212e asked this question in Q&A
Feb 15, 2024 · 1 comments · 2 replies
Discussion options

You must be logged in to vote

@m1212e Hi,

So when I make a DB call I get a type of e.g. string | null for an optional field but the typescript compiler complains because the type derived from the schema which uses Optional() results in string | undefined which is a type mismatch. Can I somehow easily resolve this without having to re map the returned types all the time?

Try the following

TypeScript Link Here

import { Type, Static, TSchema } from '@sinclair/typebox'

const Nullable = <T extends TSchema>(schema: T) => Type.Union([Type.Null(), schema])

const T = Type.Object({
   name: Nullable(Type.String()),
   level: Nullable(Type.Number()),
   enabled: Nullable(Type.Boolean())
})

type T = Static<typeof T>

Just kee…

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@m1212e
Comment options

@woss
Comment options

Answer selected by m1212e
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