TypeScript Typings
Relevant source files
The following files were used as context for generating this wiki page:
Cheerio is built with a robust TypeScript infrastructure that provides comprehensive type definitions for its jQuery-like API and DOM manipulation capabilities. The project utilizes TypeScript to ensure type safety across its diverse parsing backends (parse5 and htmlparser2) and to provide a high-quality developer experience through accurate autocompletion and static analysis.
The typing system is deeply integrated with the domhandler ecosystem, representing elements, nodes, and documents as structured TypeScript types. This allows Cheerio to maintain a "Blazingly fast" consistent DOM model while providing flexible environment support for both browser and server-side execution.
Sources: Readme.md, package.json:115-119
Core Type Architecture
Cheerio's type system is designed around the Cheerio<T> class and the CheerioAPI interface. The library exports different sets of types based on the build target (ESM, CommonJS, or Browser), ensuring that the appropriate types are loaded for the specific environment.
Type Distribution and Exports
The library manages type definitions through the exports field in package.json, mapping specific entry points to their corresponding .d.ts files.
| Entry Point | Import Type | Path to Definition |
|---|---|---|
. (Main) | Import | ./dist/esm/index.d.ts |
. (Main) | Require | ./dist/commonjs/index.d.ts |
./slim | Import | ./dist/esm/slim.d.ts |
./utils | Import | ./dist/esm/utils.d.ts |
| Browser | Import | ./dist/esm/browser/index.d.ts |
Sources: package.json:29-80
Dependency Mapping
Cheerio leverages external type definitions from the domhandler and parse5 ecosystems to define the structure of its DOM nodes.
The documentation generation via TypeDoc specifically maps internal symbols to external documentation for domhandler (e.g., Document, Element, Node) and parse5 (e.g., TreeAdapter).
Sources: website/typedoc.json:20-33, src/cheerio.spec.ts:110-115
Selection and Generic Types
The primary collection type in Cheerio is the generic Cheerio<T>, where T usually extends AnyNode from domhandler. This generic approach allows for specific typing of selections, such as Cheerio<Element> for element-only collections or Cheerio<AnyNode> for mixed node types.
Interface Extension (Module Augmentation)
Cheerio supports module augmentation, allowing developers to extend the Cheerio interface to include custom plugins while maintaining type safety.
declare module './index.js' {
interface Cheerio<T> {
myPlugin(...args: unknown[]): {
context: Cheerio<T>;
args: unknown[];
};
}
}
Sources: src/cheerio.spec.ts:7-15
Instance Isolation
The CheerioAPI is designed to isolate extensions. When a document is loaded via cheerio.load(), it returns a function that acts as a unique instance with its own prototype, preventing cross-contamination between different loaded documents.
Sources: src/cheerio.spec.ts:285-295
Linter and Compiler Configuration
Cheerio's TypeScript environment is strictly controlled via ESLint and Biome to maintain code quality and prevent common type-related errors.
TypeScript Rules and Overrides
The project utilizes typescript-eslint with specific configurations for standard files and test files (.spec.ts).
- Unnecessary Conditions: The rule
@typescript-eslint/no-unnecessary-conditionis disabled because Cheerio often interacts with plain JavaScript callers where types might lie about nullability (e.g.,this[0]on an empty selection). - Type Checking: The project uses
recommendedTypeCheckedandstylisticTypeCheckedconfigurations. - Global Variables: Specific globals are defined for test environments (Vitest), including
describe,it, andexpect.
Sources: eslint.config.js:154-180, biome.json:65-75
Compiler Service
The linting process utilizes a "Project Service" that defaults to tsconfig.json for standard files and a specific configuration for the website directory to ensure context-aware type checking.
Sources: eslint.config.js:46-51, eslint.config.js:203-212
API Type Signatures
Cheerio's API functions use overloaded signatures to handle various input types (strings, nodes, or arrays of nodes) and return types.
Attribute and Property Methods
Methods like .attr(), .prop(), and .css() utilize conditional return types based on whether they are being used as getters or setters.
| Method | Argument | Return Type | Description |
|---|---|---|---|
.attr() | None | Record<string, string> | Gets all attributes. |
.attr() | name: string | string | undefined | Gets a specific attribute. |
.attr() | name, value | Cheerio<T> | Sets an attribute (Chaining). |
.prop() | name: string | boolean | string | ... | Gets a property value. |
Sources: src/api/attributes.spec.ts:24-40, src/api/attributes.spec.ts:153-165
Loading and Parsing Options
The load method accepts a CheerioOptions object which configures the underlying parser's behavior.
- xml: Boolean or object. When
true, it useshtmlparser2for XML rendering. - scriptingEnabled: Boolean. Controls if
noscripttags are parsed as text or DOM. - sourceCodeLocationInfo: Boolean. When enabled, adds
sourceCodeLocationmetadata to nodes (supported by parse5).
Sources: src/cheerio.spec.ts:246-260, src/cheerio.spec.ts:318-350
Conclusion
The TypeScript typings in Cheerio provide a strict yet flexible framework for HTML/XML manipulation. By utilizing generics for node collections and supporting module augmentation for plugins, Cheerio maintains a type-safe environment that caters to both internal development and external consumers. The integration with the domhandler type hierarchy ensures that Cheerio remains compatible with the broader Node.js DOM ecosystem.