TypeScript全局signin函数报错,请求技术解决方案
问题解决:全局
signin函数类型声明不生效的错误 错误原因
你遇到的问题源于TypeScript新版本对全局对象类型检查的严格性:原有的NodeJS.Global接口扩展不会自动映射到标准全局对象globalThis,导致赋值时类型不兼容,触发"Element implicitly has an 'any' type"错误。
解决方案
1. 修改全局类型声明
替换原有的类型声明代码,直接在declare global块中声明全局变量类型:
import request from 'supertest'; import { app } from '../app'; // 正确的全局类型声明 declare global { var signin: () => Promise<string[]>; } // 赋值时使用globalThis(推荐)或global globalThis.signin = async () => { const email = 'test@test.com'; const password = 'password'; const response = await request(app) .post('/api/users/signup') .send({ email, password }) .expect(201); const cookie = response.get('Set-Cookie'); return cookie; }; it('responds with details about the current user', async () => { const cookie = await globalThis.signin(); // 或使用global.signin() const response = await request(app) .get('/api/users/currentuser') .set('Cookie', cookie) .send() .expect(200); expect(response.body.currentUser.email).toEqual('test@test.com'); });
2. 检查tsconfig.json配置
确保你的tsconfig.json包含Node.js类型支持:
{ "compilerOptions": { "target": "ES2020", "lib": ["ES2020"], "module": "CommonJS", "typeRoots": ["./node_modules/@types"], "types": ["node"], // 必须包含该配置以加载Node.js全局类型 "strict": true } }
替代方案(扩展globalThis接口)
若偏好接口扩展的方式,可改为:
declare global { interface globalThis { signin: () => Promise<string[]>; } }
此写法让TypeScript直接识别globalThis.signin的类型,彻底避免any类型错误。
内容的提问来源于stack exchange,提问作者Lumi Demukaj
相关产品推荐
相关产品推荐

