You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在不引入lib:dom时忽略@types/urijs中的HTMLElement类型?

Solution to Ignore HTMLElement Parameter in @types/urijs Without lib:dom

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:

  1. Create a file like src/types/urijs.d.ts in your project
  2. Add the following code:
import 'urijs';

declare module 'urijs' {
  // Redefine the URI class constructor to exclude HTMLElement
  class URI {
    constructor(value?: string | URIOptions);
  }
}
  1. Ensure your tsconfig.json includes this path in the include array:
{
  "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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:37:39