如何在不引入lib:dom时忽略@types/urijs中的HTMLElement类型?
Absolutely, there are a few clean ways to strip out the HTMLElement parameter from @types/urijs's constructor signature without enabling the dom library in your tsconfig.json. Here are the most practical approaches:
1. Custom Type Alias with Type Assertion
This is a quick, localized fix if you only need the restricted type in specific parts of your codebase:
// Import the original URI type definitions import type { URI, URIOptions } from 'urijs'; // Define a constructor type that only accepts string/URIOptions type RestrictedURIConstructor = new (value?: string | URIOptions) => URI; // Assert the default export to our restricted type const URI = require('urijs') as RestrictedURIConstructor; // Valid usage const uriFromStr = new URI('https://example.com'); const uriFromOpts = new URI({ protocol: 'https', hostname: 'example.com' }); // Invalid usage (will throw TypeScript error as expected) // const uriFromElement = new URI(document.body);
2. Local Module Augmentation (Global Fix)
For a project-wide solution that automatically applies the restricted type everywhere, create a local type declaration file to override the original @types/urijs signature:
- Create a file like
src/types/urijs.d.tsin your project - Add the following code:
import 'urijs'; declare module 'urijs' { // Redefine the URI class constructor to exclude HTMLElement class URI { constructor(value?: string | URIOptions); } }
- Ensure your
tsconfig.jsonincludes this path in theincludearray:
{ "include": ["src/**/*", "src/types/**/*"] }
Now anywhere you import URI in your project, TypeScript will only allow string or URIOptions as constructor arguments, and HTMLElement will be rejected.
3. Wrapper Function (Encapsulated Usage)
If you prefer to avoid type assertions or declaration files entirely, wrap the URI constructor in a helper function that enforces your desired parameter types:
import URI, { URIOptions } from 'urijs'; export function createURI(value?: string | URIOptions): URI { return new URI(value); } // Usage const validUri = createURI('https://example.com'); // createURI(document.body) // TypeScript error: Argument of type 'HTMLElement' is not assignable to parameter of type 'string | URIOptions | undefined'
All three methods achieve your goal of ignoring the HTMLElement type without enabling the dom library. The module augmentation approach is best for global consistency, while the alias/wrapper methods work well for scoped use cases.
内容的提问来源于stack exchange,提问作者Bohr Hew

