javascript - 获取对象属性

标签 javascript object typescript

我是 TypeScript 新手。

如何解决这个问题:

layout[self._swapEntries ? '_rows' : 'rows'].slice(0, layout.numRowsToDraw);

错误:

error TS7017: Index signature of object type implicitly has an 'any' type.

另一个问题:

 let entries = rows.selectAll("g." + Legend.LEGEND_ENTRY_CLASS).data((d) => d);

错误2:

error TS2345: Argument of type '(d: {}) => {}' is not assignable to parameter of type '(datum: {}, index: number, outerIndex: number) => {}[]'.
Type '{}' is not assignable to type '{}[]'.
Property 'length' is missing in type '{}'.

最佳答案

您可以执行以下两项操作之一:

  1. 使用接口(interface)为您的 layout 对象实现强类型定义:
interface ILayout {
    [index: string]: string[] | number, // And any other types which your object returns
    numRowsToDraw: number
}

var layout = {
    numRowsToDraw: 10
};

然后将您访问的属性显式转换为数组:

(<string[]>layout[self._swapEntries ? '_rows' : 'rows']).slice(0, layout.numRowsToDraw);
  • 使用--suppressImplicitAnyIndexErrors标志告诉编译器您希望被允许使用编译时未知的类型访问对象键
  • 关于javascript - 获取对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33232372/

    相关文章:

    javascript - 我可以使用 JavaScript 将 HTML 发送到新的选项卡/窗口并加载 CSS 吗?

    php - 避免使用 PHP 为文件 XLS 中继服务请求 Url 太长

    javascript - $.proxy, bind, call, apply 的区别

    javascript - 在 typescript 中创建唯一的关键字

    typescript - 为了将 main 与测试编译分开,需要设置哪些正确的 typescript 编译器 (tsc) 选项?

    javascript - 单击菜单中的元素后如何使汉堡菜单消失

    javascript - 如何在react redux中存储多层对象?

    java - 检查两个对象是否具有相同的属性

    javascript - 如何让 @Model 和 @Emit 在 VueJs 中与 Typescript 一起工作?

    javascript - process.env.PORT 打印奇怪的字符串