简体   繁体   English

在 Typescript 中扩大全局范围不起作用

[英]Augmenting global scope in Typescript not working

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.这是我得到的错误: 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.我注意到,调试 node_modelues(以查看幕后发生的事情)是 {globals.global.d.ts} 文件未随声明更新。

Working service globals.global.d.ts :工作服务globals.global.d.ts

declare var global: NodeJS.Global & typeof globalThis;

Not working service globals.global.d.ts :不工作服务globals.global.d.ts

declare var global: typeof globalThis;

*Apologized in advanced if this is a silly error, I'm quite new to TS* *如果这是一个愚蠢的错误,请提前道歉,我对 TS 很陌生*

如果这是方法,我不知道,但我通过添加 @types/node 作为依赖项解决了这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM