javascript - 在 TypeScript 中访问对象的子对象

标签 javascript typescript parent children

我正在尝试访问 TypeScript 中对象的子对象。

所以object1是Object的子对象。当我控制台日志对象(父级)时,我清楚地看到属性“Children”。如果展开 Children,我会看到 Object1。

enter image description here

通常在 JavaScript 中,我会做类似的事情

var child = Object.children[0];

但是,当我在 TypeScript 中执行此操作时,它会给出语法错误

error TS2339: Property 'children' does not exist on type 'DisplayObject'.

在 TS 中是否有不同的方法?

编辑

示例代码:

  this.game.world.children.forEach(function(child){
        var constructorString: string = child.constructor.toString();
        var className: string = constructorString.match(/\w+/g)[1];
        if(className=='AcheivmentButton'){
          for(var i=0; i<child.children.length; i++)
            children.push(child.children[i]);
        }
      })

最佳答案

Is there a different way to do it in TS?

没有。这只是您正在使用的对象的定义存在差异。

最快的方法是简单地使用断言:

var child = (Object as any).children[0];

更多

关于javascript - 在 TypeScript 中访问对象的子对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34032105/

相关文章:

javascript - 从 css 类中删除 width 属性

javascript - 最近表的最近表

angularjs - 如何从焦点/模糊更改父元素的类?

Typescript:使用嵌套只读属性时,类型防护无法按预期工作

typescript - 将 Object<T> 转换为 Object<A>,其中 A 包含在 T 中

jquery - 试图在每个语句中获取 this 的父级

javascript - 将 onclick 事件添加到模板

javascript - 在 d3.js 全局 map 中设置点

javascript - 是否有用于 XML 绑定(bind)的 JavaScript API——类似于 Java 的 JAXB?

typescript - 如何将字符串文字类型定义为另一种字符串文字类型的子类型?