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

时间:2019-04-28 02:37:12

标签: typescript

我想向window.history对象添加一个属性声明,但是出现了TS错误提示

我的代码:

const historyInstance = createHashHistory(); // npm hoistory module
window.history.historyInstance = historyInstance;
//              ↑ error occurred in there

我的types.ts是:

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)
}

1 个答案:

答案 0 :(得分:0)

请尝试改编Window接口,而不是改编History接口。创建一个新的*.d.ts文件,例如就您而言history.d.ts。添加以下内容:

export = global;

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

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

{
  "compilerOptions": {
    "typeRoots": ["node_modules/@types", "./types"],
    ...
  }
}

Folderstructur就像:

types/
  |--- history.d.ts
tsconfig.json