I new to and trying out Fastify with Typescript. I am unable to figure out why the name
in the const {name} = req.query
section is throwing a type error:
Property 'name' does not exist on type 'unknown'.ts(2339)
Shouldn’t the schema: already provide type inference on the name? Or do I need to further add types for the req
variable?
Full code:
import { Type } from '@sinclair/typebox';
import { FastifyPluginAsyncTypebox } from '@fastify/type-provider-typebox'
import { FastifyInstance } from 'fastify';
const plugin: FastifyPluginAsyncTypebox = async function(fastify: FastifyInstance) {
fastify.get('/', {
schema: {
querystring: Type.Object({
name: Type.String({ default: 'world' })
}),
response: {
200: Type.Object({
hello: Type.String()
})
}
}
}, (req) => {
const { name } = req.query;
return { hello: name };
});
fastify.post('/', {
schema: {
body: Type.Object({
name: Type.String()
}),
response: {
200: Type.Object({
hello: Type.String()
})
}
}
}, async (request) => {
const { name } = request.body;
return { hello: name || 'world' };
});
}
export default plugin;
Other files:
tsconfig.json
{
"extends": "fastify-tsconfig",
"compilerOptions": {
"outDir": "build",
"target": "es2018",
"lib": ["es2018"]
}
}
package.json
{
"name": "fastify",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"build": "tsc -p tsconfig.json",
"start": "node index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"fastify": "^4.27.0"
},
"devDependencies": {
"@fastify/autoload": "^5.8.2",
"@fastify/swagger": "^8.14.0",
"@fastify/swagger-ui": "^3.0.0",
"@fastify/type-provider-typebox": "^4.0.0",
"@sinclair/typebox": "^0.32.30",
"@tsconfig/recommended": "^1.0.6",
"@types/node": "^20.12.11",
"fastify-tsconfig": "^1.0.0",
"typescript": "^5.4.5"
}
}
Original repo: https://github.com/mcollina/type-safe-fastify/blob/main/routes/root.ts
Original video: https://www.youtube.com/watch?v=hx6jy3MzQzw