首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何向TS内部对象添加属性?

如何向TS内部对象添加属性?
EN

Stack Overflow用户
提问于 2019-04-28 10:37:12
回答 1查看 70关注 0票数 0

我想向window.history对象添加一个属性声明,但收到TS错误提示

我的代码:

代码语言:javascript
运行
复制
const historyInstance = createHashHistory(); // npm hoistory module
window.history.historyInstance = historyInstance;
//              ↑ error occurred in there

我的types.ts是:

代码语言:javascript
运行
复制
interface IHistory extends History {
  historyInstance: any;
}

interface Window {
  history: IHistory;
// ↑ (property) Window.history: History
// All declarations of 'history' must have identical modifiers.ts(2687)
// Subsequent property declarations must have the same type.  Property // 'history' must be of type 'History', but here has type 'IHistory'.ts(2717)
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-04-28 20:00:34

试着去适应History接口,而不是去适应Window接口。创建一个新的*.d.ts文件,例如,在您的示例中,可能是history.d.ts。添加以下内容:

代码语言:javascript
运行
复制
export = global;

declare global {
  interface History {
    historyInstance: any;
  }
}

您应该将新创建的history.d.ts放到types/文件夹中,然后您必须修改您的tsconfig.json

代码语言:javascript
运行
复制
{
  "compilerOptions": {
    "typeRoots": ["node_modules/@types", "./types"],
    ...
  }
}

Folderstructur类似于:

代码语言:javascript
运行
复制
types/
  |--- history.d.ts
tsconfig.json
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55886549

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档