0

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.

1 Answer 1

1

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
1
  • Thank you arash. You made me sure that there is no way to do that. I used function overloading and i got other strange errors from ts. thank you :)
    – Saman
    Nov 21, 2022 at 9:26

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.