我想向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)
}
答案 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