sinclairzx81 / typebox

Json Schema Type Builder with Static Type Resolution for TypeScript
Other
4.65k stars 150 forks source link

tsconfig "strict": true - ignore modifiers #814

Closed DamienDeSousa closed 4 months ago

DamienDeSousa commented 4 months ago

Hello !

I'm currently facing an issue using the Type.Optional modifier.

I'm using @sinclair/typebox:0.24.43 version. I'm on node 18. I use the framework fastify version 4.10.2.

I'm using your package to type the response of my routes. In one of them, I set an optional attribute:

myAttr: Type.Optional(Type.Object({...}))

But when I send the request, the server generate the following error:

Technical error : Error: \"myAttr\" is required!

I investigated and found in your documentation the Type.Strict(). It ignore the modifiers. I don't use this one in my code but in my tsconfig, there is the "strict": true.

When I set "strict": false, the request works fine !

How can I avoid the previous error in my API without setting the "strict": false in my tsconfig ?

sinclairzx81 commented 4 months ago

@DamienDeSousa Hi,

It might be helpful to provide a code example here. But just a couple of things to provision with:

1) You SHOULD always set strict: true inside tsconfig.json (this is a TypeBox requirement) 2) You SHOULD NOT use Type.Strict() (as this is a utility function that wouldn't contribute to this error)

So just make sure your project is setup with the above...


So, I'm not sure where the Technical error : Error: \"myAttr\" is required! would originate. It's not an error generated by TypeBox and it doesn't read like an error generated from Fastify. However, your code should be setup similar to the following.

TypeScript Link Here

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

const app = Fastify()

type Response200 = Static<typeof Response200>
const Response200 = Type.Object({
  myAttr: Type.Optional(Type.Object({
    x: Type.Number(),
    y: Type.Number(),
    z: Type.Number()
  }))
})

app.get<{ Reply: Response200 }>('/', {
  schema: {
    response: {
      200: Response200
    }
  }
}, (req, reply) => {
  reply.send({ myAttr: { x: 1, y: 2, z: 3 } })
})

This would be a standard TypeBox/Fastify setup. If you can test / compare the above code the code running your side, this might help provide a basis to resolve the issue. Alternatively, if you can provide me a reproduction of the issue you see (code + full TypeBox type), I may be able to offer additional assistance.

Let me know how you go S

DamienDeSousa commented 4 months ago

Thank you for your answer !

I found the problem.

It was because I used Type.Required() in my schema. Even if myAttr was set to optional, the Required set it to required in the json schema.

OK computer science is still computer science !

Ty for your time !