Home > Software engineering >  Typescript - how can i add a custom property to express. Request with two or more types?
Typescript - how can i add a custom property to express. Request with two or more types?

Time:11-21

I have a problem. I know how to add a custom property to Express.Request, but i dont know how to give that custom property two or more types. For example i have a.ts and b.ts. These file export a function as default. And i import them in c.ts. All those functions add the same property to Express.Request. But those functions, add different types of functions as value! Look at this example: a.ts:

    declare module "express-serve-static-core" {
      interface Request {
        store: (name: string) => number
      }
    }
    
    const func1 = (req:Request, res:Response) => {
       req.store = (name) => {
       return setInStore(name)
       }
    }
export default func1;

b.ts:

    declare module "express-serve-static-core" {
      interface Request {
        store: (key: number) => string
      }
    }
    
    const func2 = (req:Request, res:Response) => {
       req.store = (key) => {
          return getFromStore(key);
       }
    }
export default func2;

but when i set the type in b.ts, i will get error from a.ts. it says that type (name: string) => number is not assignable to type (key: number) => string.

and i think that there is an other way instead of using conditional types. so how can i change the type of store property to (name: string) => number if user used the func1 middleware and change the type of store to (key: number) => string if user used func2 thanks for help.

CodePudding user response:

I am not express user. maybe you can config the type through generics too which is easier

anyway, what you want to do is not possible. however, you can go with one of these solutions:

1. unions

if the store functions supports both value, then it is not important which type in which function you are using... so you can use union

(key: string | number) => void

2. more specific function name

split the store function into 2 seperate functions like this

storeByName: (name: string) => void
storeById: (id: number) => void
  • Related