Question:
What if the property 'X' does not exist on type 'FastifyContext<unknown>'?

Problem

I want to add the token: string field to the FastifyContext interface. For this purpose I have created the following file structure:


projectDir

|__src

|  |__@types

|  |  |__fastify

|  |  |  |__index.d.ts

|  |__api

|  |  |__authHook.ts

|__tsconfig.json


Content of src/@types/fatify/index.d.ts:


declare module 'fastify' {

    export interface FastifyContext<ContextConfig>{

        token: string

    }

}


Content of src/api/authHook.ts


import {FastifyRequest, FastifyReply} from "fastify";



export default async function authHook(request: FastifyRequest, reply: FastifyReply): Promise<void>{

    // Some logic 

    const token = "example_token" // some result from logic 

    request.context.token = token;

}


Content of tsconfig.json:


{

  "compilerOptions": {

     ...

     "typeRoots": ["src/@types"],

     ...

  }

}


But when I run the code I get the following error:


Property 'token' does not exist on type 'FastifyContext<unknown>'.


What did I do wrong?


Solution


import { onRequestHookHandler } from "fastify";


declare module "fastify" {

  export interface FastifyRequestContext {

    token: string;

  }

}


const authHook: onRequestHookHandler = async function (request, reply) {

  const token = "example_token";

  request.context.token = token;

};


export default authHook;


Suggested blogs:

>Why Typescript does not allow a union type in an array?

>Narrow SomeType vs SomeType[]

>Create a function that convert a dynamic Json to a formula in Typescript

>How to destroy a custom object within the use Effect hook in TypeScript?

>How to type the values of an object into a spreadsheet in TypeScript?

>Type key of record in a self-referential manner in TypeScript?

>How to get the last cell with data for a given column in TypeScript?

>Ignore requests by interceptors based on request content in TypeScript?

>Create data with Typescript Sequelize model without passing in an id?

>How to delete duplicate names from Array in Typescript?


Nisha Patel

Nisha Patel

Submit
0 Answers