to get some context I'm working in a microservices app where I have two similar services with practically the same packages. In order to make some testing I add a function to the global scope and augmented it to avoid typescript errors. The problem is that in one service is working with no errors and in the other no.
Here is the code:
import { MongoMemoryServer } from 'mongodb-memory-server';
import mongoose from 'mongoose';
import jwt from 'jsonwebtoken';
// --- This is not working
declare global {
namespace NodeJS {
interface Global {
signup(id?: string): string[];
}
}
}
// ---
jest.mock('./../nats-wrapper.ts');
let mongo: any;
beforeAll(async () => {
process.env.JWT_KEY = 'only_for_testing';
mongo = new MongoMemoryServer();
const mongoUri = await mongo.getUri();
await mongoose.connect(mongoUri, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
});
beforeEach(async () => {
jest.clearAllMocks();
const collections = await mongoose.connection.db.collections();
for (let collection of collections) {
await collection.deleteMany({});
}
});
afterAll(async () => {
await mongo.stop();
await mongoose.connection.close();
});
// --- This is not working
global.signup = (id?:string) => {
// Build a JWT payload. {id, email}
const payload = {
id: id || new mongoose.Types.ObjectId().toHexString(),
email: 'test@test.com',
};
// Create the JWT!
const token = jwt.sign(payload, process.env.JWT_KEY!);
// Build session Object
const session = { jwt: token };
// Turn sesion into JSON
const sessionJSON = JSON.stringify(session);
// Encode to Base64
const base64 = Buffer.from(sessionJSON).toString('base64');
// return a string with the enconded data;
return [`express:sess=${base64}`];
};
// ---
And this is the error I'm getting: TS7017: Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature.
What I noticed, debugging the node_modelues (to see what is happening behind scenes), is that the {globals.global.d.ts} file is not updating with the declaration.
Working service globals.global.d.ts:
declare var global: NodeJS.Global & typeof globalThis;
Not working service globals.global.d.ts:
declare var global: typeof globalThis;
*Apologized in advanced if this is a silly error, I'm quite new to TS*