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

我试图在窗口对象上附加属性.这是我的代码.

 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 Index对象类型的签名隐式具有类型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;
    }
};
点赞