How to properly decorate request in TypeScript #5100
-
I'm trying this code and it fails to compile and throws an error.
Compile Error
Fastify version: tsconfig.json {
"compilerOptions": {
"target": "ES2017",
"module": "commonjs",
"rootDir": "./src",
"allowJs": false,
"outDir": "./dist",
"noEmitOnError": true,
"preserveConstEnums": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"strictPropertyInitialization": true,
"useUnknownInCatchVariables": true,
"alwaysStrict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noUncheckedIndexedAccess": true,
"allowUnreachableCode": true,
"skipLibCheck": true,
"experimentalDecorators": true
},
"include": ["./src/**/*.ts"],
"exclude": ["node_modules"]
} |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments 1 reply
-
Hey! Remember to do declare module 'fastify' {
interface FastifyRequest {
user: {
id: number
}
}
} |
Beta Was this translation helpful? Give feedback.
-
In my declare module 'fastify' {
interface FastifyRequest {
user: {
id: number;
};
}
} |
Beta Was this translation helpful? Give feedback.
-
Attached my |
Beta Was this translation helpful? Give feedback.
-
@metcoder95 Thanks! But augmenting interface in "scripts": {
"build": "tsc ",
"start": "node ./dist/server.js",
"dev": "ts-node --files ./src/server.ts "
}, I was able to figure this out when I directly tried building and it did not give any error at compile time. Again Thanks for your help. |
Beta Was this translation helpful? Give feedback.
-
create file fastify.d.ts in src/@types declare module "fastify" {
export interface FastifyInstance<
HttpServer = http.Server,
HttpRequest = http.IncomingMessage,
HttpResponse = http.ServerResponse
> {
blipp(): void; // declare here
}
} |
Beta Was this translation helpful? Give feedback.
You need to do the augmentation on the same place as the application code, otherwise, it rewrites the module type definition, leading to errors. A working example might be: