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

如何在TypeScript中全局重写history对象的state类型?

解决TypeScript扩展History接口让history.state包含key属性的问题

不用重新声明history全局变量(这会导致类型不一致报错),利用TypeScript的接口合并特性直接扩展全局History接口即可,以下是两种场景的实现方式:

场景1:当前文件是脚本文件(无import/export)

直接在文件顶部扩展History接口:

// 扩展全局History接口,为state添加key属性
interface History {
  state: HistoryState & {
    key?: string;
  };
}

// 直接使用,编译器会识别state的key属性
const currentKey = history.state.key;

这里用HistoryState(lib.dom.d.ts中定义的原生state类型)和自定义的{key?: string}做交叉类型,既保留原生state的所有属性,又新增key字段。

场景2:当前文件是模块文件(有import/export)

如果文件包含import/export语句,会被视为模块,此时需要用declare global包裹接口扩展,将其作用于全局作用域:

import { someUtil } from './utils';

// 在模块内扩展全局接口
declare global {
  interface History {
    state: HistoryState & {
      key?: string;
    };
  }
}

// 使用扩展后的history类型
function getCurrentHistoryKey() {
  return history.state.key;
}

export { getCurrentHistoryKey };

关键说明

TypeScript允许在同一作用域下多次声明同名接口,编译器会自动合并接口的属性定义。这种方式不需要重新声明history变量,从根源避免了"后续变量声明类型必须一致"的报错,同时让编译器识别到history.state的key属性。

内容的提问来源于stack exchange,提问作者Chris Hamilton

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 14:40:29