我正在尝试在窗口对象上附加属性。这是我的代码。
cbid:string ='someValue';
window[cbid] = (meta: any) => {
tempThis.meta = meta;
window[cbid] = undefined;
var e = document.getElementById(cbid);
e.parentNode.removeChild(e);
if (meta.errorDetails) {
return;
}
};
编译器开始抛出以下错误。
对象类型的 TypeScript 索引签名隐式具有类型 any
谁能告诉我哪里做错了?
最佳答案
一个快速修复方法是允许将任何内容分配给窗口对象。您可以通过编写...
interface Window {
[propName: string]: any;
}
...在您的代码中的某处。
或者您可以使用 --suppressImplicitAnyIndexErrors
进行编译,以在分配给任何对象的索引时禁用隐式任何错误。
不过,我不推荐这两个选项中的任何一个。理想情况下最好 not to assign to window , 但如果你真的想那么你应该在一个属性上做所有事情然后定义一个与分配给它的内容相匹配的索引签名:
// define it on Window
interface Window {
cbids: { [cbid: string]: (meta: any) => void; }
}
// initialize it somewhere
window.cbids = {};
// then when adding a property
// (note: hopefully cbid is scoped to maintain it's value within the function)
var cbid = 'someValue';
window.cbids[cbid] = (meta: any) => {
tempThis.meta = meta;
delete window.cbids[cbid]; // use delete here
var e = document.getElementById(cbid);
e.parentNode.removeChild(e);
if (meta.errorDetails) {
return;
}
};
关于对象类型的 TypeScript 索引签名隐式具有类型 any,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33350313/