TypeScript中无法导入@types/chai-http类型声明,如何直接导入?
Hey there! I’ve run into nearly identical headaches setting up TypeScript test environments for REST APIs, so let’s walk through how to get those chai-http types playing nice with your require() setup.
Step 1: Double-Check Your Type Dependencies
First, make sure you’ve installed the official type definitions for both chai and chai-http—this is a common gotcha if they’re missing or misinstalled. Run this in your project root:
npm install --save-dev @types/chai @types/chai-http # Or for yarn users: yarn add -D @types/chai @types/chai-http
Step 2: Explicitly Import Types and Extend Chai’s Typing
Since you’re using require() instead of ES6 imports, you need to tell TypeScript that chai has been extended by the chai-http plugin. Here’s how to do this directly in your test file:
// Require the core modules first const chai = require('chai'); const chaiHttp = require('chai-http'); // Import the type definitions we need import type { ChaiHttp } from '@types/chai-http'; import type { Assertion } from '@types/chai'; // Let TypeScript know chai is being extended with chai-http chai.use(chaiHttp as ChaiHttp); // Grab expect with proper typing attached const expect = chai.expect as () => Assertion; // This line should now work without compiler errors! expect(res).to.have.status(201);
Step 3: Global Type Declaration (For Cross-Test File Convenience)
If you want the types available across all test files without repeating the above code, create a custom type declaration file (e.g., test/types.d.ts):
import 'chai'; import { ChaiHttp } from '@types/chai-http'; // Extend chai's core type to include chai-http functionality globally declare module 'chai' { interface Chai extends ChaiHttp {} }
Then ensure this file is included in your tsconfig.json:
{ "include": ["src/**/*", "test/**/*", "test/types.d.ts"] }
Step 4: Tweak TypeScript Config (If Needed)
If you’re still seeing errors, verify these settings in tsconfig.json:
- Set
"module": "CommonJS"(matches your require() usage) - Enable
"esModuleInterop": trueto smooth compatibility between CommonJS and ES modules - Confirm
"typeRoots"includes"./node_modules/@types"(this is usually default, but worth checking)
The core issue here is that chai-http modifies chai’s prototype, so TypeScript needs explicit hints that chai’s types have been augmented. By importing the ChaiHttp type and either asserting it in your test file or extending the module declaration, you give TypeScript the context it needs to recognize methods like have.status().
内容的提问来源于stack exchange,提问作者Loic Coenen

