I am trying to convert my js code to ts code, one part is the extending an "express-session" interface to add custom properties to an interface. I have defined a types.d.ts file for my global types, in it i have the following:
types.d.ts
declare module 'express-session' {
export interface CustomSessionData {
user?: User_t;
}
interface SessionData extends CustomSessionData {}
}
export = {};
My IDE and Compiler are fine with importing CustomSessionData and SessionData interfaces where they are being used:
middleware.ts
import { CustomSessionData } from 'express-session';
export default function useSession(
fn: (
session: Session,
setSession: (new_session: CustomSessionData | undefined) => void
) => void
) {
return (req: Request, res: Response, next: () => void) => {
const session: Session = req.session;
const setSession = (new_data: CustomSessionData | undefined) => {
req.session = { ...session, ...new_data } as Session;
};
fn(session, setSession);
next();
};
}
However when i then try to use the useSession function, and mutate the session.user property, the IDE accepts this, giving autocomplete, but the compiler throws an error, claiming "Property 'user' does not exist on type 'SessionData'. Note SessionData extends CustomSessionData so the property should exist.
I dont understand why the compiler wont recognize this but the IDE does, so help in finding out why would be appreciated.
I am compiling with ts-node.
tsconfig
{
"compilerOptions": {
"target": "ES2020"
"module": "CommonJS"
"moduleResolution": "node"
"allowJs": true
"allowSyntheticDefaultImports": true
"esModuleInterop": true
"forceConsistentCasingInFileNames": true
"strict": true
"skipDefaultLibCheck": true,
},
"exclude": ["node_modules", "./build/**/*"],
"include": ["./**/*.ts", "types"]
}
types.d.ts is in the included types/ folder
I have tried changing my tsconfig to add:
"include": ["types"]
I have also tried using following:
- How To Get Typescript Compiler To See My Global Types?
- typescript - Includes types in paths, but not compile them
- Global types in typescript
Apologies for the large code snippets with limited context, i have been trying to fix this on and off for the last week and don't know what is wrong.