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

标签 typescript

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

 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/

相关文章:

typescript 根据输入参数返回对象键

typescript - 错误 TS2322 : Type '{ id: string; }' is not assignable to type 'ApiModelFilter<M>'

typescript - 如何创建第二个参数依赖于第一个参数的 Typescript 函数?

node.js - 我应该为错误做些什么对于异步测试和 Hook ,确保调用 "done()";如果返回一个 Promise,确保它 resolve

typescript - 限制方法中的接口(interface)类型参数

image - ionic 3 : Print image using Bluetooth printer

javascript - 有没有办法在 Typescript 的包装函数中动态键入函数?

typescript - Angular 6 将可注入(inject)数组传递给 app.module.ts 中的提供程序会导致 : "Error in Cannot read property ' length' of undefined"

Javascript/Typescript 从一个嵌套数组更新数据到另一个数组

javascript - react typescript |如何使用 tailwind 启用暗模式?