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

如何在TypeScript中扩展jQuery并从同一模块导出额外类型?

如何在TypeScript中扩展jQuery并从同一模块导出额外类型?

嘿,我来帮你搞定这个问题!你现在在为jQuery Terminal完善TypeScript类型定义,想要在同一个模块里既扩展jQuery的原有类型,又导出自己的额外类型对吧?这事儿在TypeScript里其实有很清晰的实现方式,我给你拆解着说:

首先,你得在jquery.terminal模块里先引入jQuery的基础类型,这样才能合法地扩展它的接口——毕竟TypeScript需要知道你要扩展的“原型”是什么样的。然后,你可以直接在模块里定义并导出自己的自定义类型,同时完成对jQuery接口的扩展,两者完全可以在同一个模块里实现。

给你看个贴合你现有代码的示例:

declare module 'jquery.terminal' {
  // 先引入jQuery的核心类型,确保能正确扩展
  import type { JQueryStatic, jqXHR } from 'jquery';

  // 先定义你需要的额外类型,直接用export导出就行
  export type AnyFunction = (...args: any[]) => any;
  export type MapFunction = (value: AnyFunction, key: string) => AnyFunction;
  export type JSONObject = { [key: string]: any };

  // 扩展jQuery的JQueryStatic接口,TypeScript会自动和原有接口合并
  export interface JQueryStatic extends JQueryStatic {
    omap(object: { [key: string]: AnyFunction }, fn: MapFunction): { [key: string]: AnyFunction };
    jrpc(url: string, method: string, params: any[], success?: (json: JSONObject, status: string, jqxhr: jqXHR) => void, error?: (jqxhr: jqXHR, status: string) => void): void;
    // 这里可以继续补充你提到的terminal相关方法的类型定义
    terminal(selector: string | Element, options?: TerminalOptions): Terminal;
  }

  // 导出你需要的其他自定义类型,比如Terminal的配置项和类本身
  export interface TerminalOptions {
    prompt?: string;
    greetings?: string;
    // 按需添加更多配置字段
  }

  export class Terminal {
    echo(content: string | HTMLElement): void;
    prompt(): void;
    // 按需添加Terminal的其他方法和属性
  }
}

这里有几个关键点要注意:

  • 接口合并:TypeScript支持同名接口的自动合并,所以你在模块里定义的JQueryStatic会和jQuery自带的JQueryStatic接口合并,这样用户使用$时,就能看到你新增的omap、jrpc这些方法的类型提示。
  • 类型导出:你自定义的AnyFunction、Terminal这些类型,直接用export声明后,用户在导入jquery.terminal模块时就能同时获取到——比如用户可以这样用:
import $ from 'jquery';
import 'jquery.terminal';
import type { Terminal, TerminalOptions } from 'jquery.terminal';

// 这里$已经有你扩展的方法类型提示了
const mapped = $.omap({ foo: () => 'bar' }, (fn) => () => fn().toUpperCase());

// 也能直接使用你导出的自定义类型
const termOptions: TerminalOptions = { prompt: '> ' };
const term = $.terminal('#terminal', termOptions);
term.echo('Welcome to jQuery Terminal!');
  • 模块作用域:因为你是在jquery.terminal这个模块里做的扩展,不需要额外的全局声明文件,用户只要导入这个模块,TypeScript就会自动加载所有扩展和自定义类型,非常方便。

要是你还有细节上的疑问,比如某个方法的类型怎么细化,或者怎么处理更复杂的接口合并,随时调整就行!

备注:内容来源于stack exchange,提问作者jcubic

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.13 17:38:19