对象类型的 TypeScript 索引签名隐式具有类型 any

Aj1*_*Aj1 5 typescript

我正在尝试在 window 对象上附加属性。这是我的代码。

 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;
         }
     };
Run Code Online (Sandbox Code Playgroud)

编译器开始抛出以下错误。

对象类型的 TypeScript 索引签名隐式具有类型 any

有人可以告诉我我在哪里做错了吗?

Dav*_*ret 3

一个快速修复方法是允许将任何内容分配给窗口对象。你可以通过写来做到这一点...

interface Window {
    [propName: string]: any;
}
Run Code Online (Sandbox Code Playgroud)

...你的代码中的某个地方。

或者,您可以进行编译以--suppressImplicitAnyIndexErrors在分配给任何对象上的索引时禁用隐式任何错误。

但我不推荐这两个选项。理想情况下,最好不要分配给 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;
    }
};
Run Code Online (Sandbox Code Playgroud)