【问题标题】:How to access nested interface types如何访问嵌套接口类型
【发布时间】:2017-11-01 21:08:15
【问题描述】:

我有一个接口,它有第二个接口作为值,如下所示。但是当我尝试访问嵌套值时,我得到一个错误。访问嵌套接口值的正确方法是什么?

interface Results {
    pass: number;
    fail: number;
}

interface Build {
    name: string;
    results: Results;
}

var obj: Build = {
    name: "test",
    results: {
        pass: 3,
        fail: 2
    }
}

目前,我正在尝试这样访问它,但没有运气:

obj.results.pass

我得到的错误:ERROR TypeError: Cannot set property 'pass' of undefined

【问题讨论】:

  • 应该是results: Results而不是results: Item
  • 你得到什么错误?
  • 你是对的,@ExplosionPills
  • ERROR TypeError: Cannot set property 'pass' of undefined @Dethariel

标签: typescript interface nested


【解决方案1】:

您遇到的错误是运行时错误(JavaScript 执行引擎),而不是编译错误(TypeScript 编译器)。

这是因为您的obj.results 等于undefined

const test: Build = {};
test.results.pass; // ERROR TypeError: Cannot set property 'pass' of undefined

我建议您在访问其子属性之前检查results 属性值:

if (test.results) {
  test.results.pass;
}

【讨论】:

  • 我相信你是对的。我如何先给 results 属性本身一个值,因为它只有属性?
【解决方案2】:

对于那些稍后看这个的人,我不得不在 obj 中创建一个 Result 对象,例如:

this.build["results"] = { pass: 0, fail: 0};

然后能够通过像这样访问它们来访问和更改通过和失败:

this.build["results"].pass = #
this.build["results"].fail = #

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-02
    • 2020-08-01
    • 2020-01-01
    • 1970-01-01
    • 2016-09-08
    相关资源
    最近更新 更多