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
Uh oh!
There was an error while loading. Please reload this page.
-
tl;dr
You can use
Type.Unsafeto change the output type of a schema such as to cast a formattedstringto 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.iddoes 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.paramsis a union for example:There is no longer a place to put the
as UUIDas we did before.The solution I found here is to use
Type.Unsafeto do an unsafe cast of the type in the schema:Now the type of
request.params.idwill 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