Using Type.Unsafe to cast formatted string type to template string literal type #568
stefee
started this conversation in
Show and tell
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
tl;dr
You can use
Type.Unsafe
to change the output type of a schema such as to cast a formattedstring
to a template literal type in a validation schema:I wanted to share for anyone that is trying to figure out how to do this because it took me forever to figure this out.
The scenario is I'm using TypeBox as a type provider for Fastify which is using Ajv schema under the hood for parsing and validation of request params. My route handler is expecting a UUID string parameter:
The UUID type imported from the crypto module is a template string literal type:
The code example fails because
request.params.id
does not get cast to the type UUID despite being validated using{ format: "uuid" }
in the schema.We could do the following:
However this doesn't work in every case such as if the type of
request.params
is a union for example:There is no longer a place to put the
as UUID
as we did before.The solution I found here is to use
Type.Unsafe
to do an unsafe cast of the type in the schema:Now the type of
request.params.id
will beUUID
- or in the union case the type of params is{ kind: "a"; id: string } | { kind: "b"; id: UUID }
as we would expect.Beta Was this translation helpful? Give feedback.
All reactions