如何扩展@types/mocha的Context类?类型定义不生效排查
Let's break down the possible issues that are stopping your custom Mocha Context types from working, and fix them one by one:
1. You used a class instead of an interface for type merging
The official @types/mocha package defines Mocha.Context as an interface, not a class. TypeScript only lets you merge interfaces within the same namespace—classes can't be extended this way.
Update your d.ts file to use an interface instead:
declare namespace Mocha { interface Context { client: IClient; bus: IBus; testNumber: number; connectionParams: ConnectionParams; } }
2. Double-check your tsconfig.json setup
Make sure TypeScript is actually picking up your custom type file:
- Confirm the path in the
filesarray is correct relative to yourtsconfig.json. For example, if yourmocha.d.tslives in./test/types/, the entry should be"./test/types/mocha.d.ts". - If you use the
includefield, ensure the directory holding yourd.tsis included (like"include": ["src/**/*", "test/**/*"]). You might not even need thefilesfield ifincludecovers the file. - Watch out for conflicting
typeRootsortypessettings. If you've settypeRoots, make sure it includes the folder with your custom types, or add"mocha"to thetypesarray to explicitly load Mocha's official types alongside yours.
3. Use regular functions (not arrow functions) in your tests
Arrow functions bind this to the outer scope, not the Mocha Context instance. TypeScript can't infer the correct this type if you use arrows, so you'll never get hints for your custom properties.
Stick to regular functions for beforeEach and test cases:
beforeEach(function() { this.client = createClient(); // `this` is now typed as Mocha.Context with your custom properties }); it('should interact with the client', function() { expect(this.client).toBeDefined(); // Type hints should work here now! });
4. Make sure dependent types are accessible
If IClient, IBus, or ConnectionParams are defined in other files, ensure they're visible to your d.ts:
- If they're module-level types (exported from a
.tsfile), import them at the top of yourmocha.d.ts:import { IClient, IBus, ConnectionParams } from '../path/to/your/types'; declare namespace Mocha { interface Context { client: IClient; // ... other properties } } - If they're global types, make sure their definition files are loaded by TypeScript (either via
includeorfilesin your tsconfig).
5. Clear TypeScript's cache
Sometimes TypeScript hangs onto old type definitions. If you're using VS Code, run TypeScript: Restart TS Server from the command palette (Ctrl+Shift+P). You can also delete cached files in node_modules/.cache if you're using a build tool like Vitest or Webpack.
内容的提问来源于stack exchange,提问作者Illorian

