It's the same question than: How do I extend the typings of Express.Application to give typings for app.locals but the suggested solution doesn't work for me.
I have server.ts :
const express = require('express');
type Message = {
author: string,
message: string
}
declare global {
namespace Express {
interface Locals {
chat: Array
}
}
}
/** Setup Express server */
const app = express();
app.use(express.json());
let sampleMessage: Message = {
author: 11
}
app.locals.resetChat = () => {
app.locals.chat = [{author: 11, message: 'Welcome to the chat!'}];
};
app.locals.resetChat();
export {};
I purposefully wrote 2 mistakes, in order to see if type checking works. When I run tsc server.ts, it only catches the error at let sampleMessage = ... but not the affectation to app.locals.chat = .... Here's the output:
server.ts:24:3 - error TS2322: Type 'number' is not assignable to type 'string'.
24 author: 11
~~~~~~
server.ts:6:3
6 author: string,
~~~~~~
The expected type comes from property 'author' which is declared here on type 'Message'
Found 1 error in server.ts:24
What is wrong. I don't understand how the declare global and namespace Express work…