I am facing an issue with extending the User
type in express.js
by including an express.d.ts
declaration file in my project. Although adding the declaration file removes the error indicators in VS Code, Typescript is failing to compile. I am encountering errors like
TS2339: Property 'id' does not exist on type 'User'
during compilation even though intellisense is able to recognize the declarations.
express.d.ts
import { Channel, User as DbUser } from '../entities'
declare global {
namespace Express {
interface Request {
channel?: Channel
}
//User already exists on Request and is of type {}
interface User extends DbUser {
}
}
}
tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"target": "ES2017",
"pretty": true,
"strict": true,
"alwaysStrict": true,
"noImplicitThis": false,
"noUnusedLocals": true,
"strictNullChecks": false,
"noUnusedParameters": false,
"noFallthroughCasesInSwitch": true,
"baseUrl": ".",
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"esModuleInterop": true,
"lib": [ "ESNext" ]
}
}
package.json
{
"dependencies": {
// ...brevity
"express": "^4.17.1",
"ts-loader": "^5.4.5",
"ts-node": "^8.6.2",
"typescript": "^3.7.5"
},
"devDependencies": {
// ...brevity
"@types/express": "^4.17.2",
"@types/express-serve-static-core": "^4.17.2",
}
}
compilation error TSError: ⨯ Unable to compile TypeScript: src/middleware/authorize.ts(8,34): error TS2339: Property 'session' does not exist on type 'Request'. src/middleware/authorize.ts(10,35): error TS2339: Property 'badges' does not exist on type 'User'. src/middleware/authorize.ts(25,34): error TS2339: Property 'session' does not exist on type 'Request'. src/middleware/authorize.ts(27,35): error TS2339: Property 'badges' does not exist on type 'User'. src/middleware/authorize.ts(42,34): error TS2339: Property 'session' does not exist on type 'Request'. src/middleware/authorize.ts(44,35): error TS2339: Property 'badges' does not exist on type 'User'.