@fastify/type-provider-json-schema-to-ts
A Type Provider for json-schema-to-ts
Install
npm i @fastify/type-provider-json-schema-to-ts
TypeScript requirements
It is required to use TypeScript@4.3
or above with
strict
mode enabled and
noStrictGenericChecks
disabled. You may take the below configuration (tsconfig.json
)
as an example.
{
"compilerOptions": {
"strict": true,
"noStrictGenericChecks": false
}
}
Plugin definition
Note
When using plugin types, withTypeProvider is not required in order to register the plugin
const plugin: FastifyPluginAsyncJsonSchemaToTs = async function (
fastify,
_opts
) {
fastify.get(
"/",
{
schema: {
body: {
type: "object",
properties: {
x: { type: "string" },
y: { type: "number" },
z: { type: "boolean" },
},
required: ["x", "y", "z"],
} as const,
},
},
(req) => {
const { x, y, z } = req.body;
}
);
};
Using References from a Shared Schema
JsonSchemaToTsProvider takes a generic that can be passed in the Shared Schema
as shown in the following example
const userSchema = {
type: "object",
additionalProperties: false,
properties: {
givenName: { type: "string" },
familyName: { type: "string" },
},
required: ["givenName", "familyName"],
} as const;
const sharedSchema = {
$id: "shared-schema",
definitions: {
user: userSchema,
},
} as const;
const fastify =
Fastify().withTypeProvider<
JsonSchemaToTsProvider<{ references: [typeof sharedSchema] }>
>();
fastify.get(
"/profile",
{
schema: {
body: {
type: "object",
properties: {
user: {
$ref: "shared-schema#/definitions/user",
},
},
required: ['user'],
},
} as const,
},
(req) => {
const { givenName, familyName } = req.body.user;
}
);