繁体   English   中英

在打字稿/ angularJs 2中,类型“ JSON”上不存在属性“名称”

[英]Property 'name' does not exist on type 'JSON' in typescript / angularJs 2

我在我的REST api应用程序中使用angularjs 2中的打字稿语言,问题是-打字稿给出了编译时错误

[ts] Property 'name' does not exist on type 'JSON'.any

当我尝试访问JSON对象时,我的功能代码如下

createPerformanceChart(data: JSON) {
    // Show Up the Fund Details Data 
    var details: any;
    for(var j = 0 ; j < Object.keys(this.funds).length; j++)
    {
        if(data.name == this.funds[j].name) // data.name throws Error
        {
            details = this.funds[j];
        }
    }
}

如何转换JSON或访问JSON对象-这样它不会引发编译时错误,而是让我编译代码。

如果你想做强类型

您必须使用例如interface将响应类型( JSON )更改为更具体的内容:

interface IPerformanceData {
  name: string;
}

然后将其用作传入响应的类型:

createPerformanceChart(data: IPerformanceData) {
  // you can now use: data.name
}

如果你不在乎

只要使其成为any类型:

createPerformanceChart(data: any) {
  // you can now use any property: data.*
}

您可以通过以下方法检查JSON数据中是否存在该名称字段:

createPerformanceChart(data: JSON) {
    // Show Up the Fund Details Data 
    var details: any;
    for(var j = 0 ; j < Object.keys(this.funds).length; j++)
    {
        if(data.name == this.funds[j].name && data.name) <-- check if data.name is present
        {
            details = this.funds[j];
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM