Typescript/angularJs 2中的'JSON'类型不存在属性'name' [英] Property 'name' does not exist on type 'JSON' in typescript / angularJs 2
问题描述
我在我的REST api应用程序中使用angularjs 2中的打字稿语言,问题是-打字稿给出了
I am using typescript language in angularjs 2 to my REST api application, the problem is - typescript gives compile time error of
[ts]属性'name'在类型'JSON'上不存在.任何
当我尝试访问JSON对象时,我的功能代码在下面
WHEN I TRY TO ACCESS INCOMING JSON Object, my function code is below
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对象-这样它不会引发编译时错误并让我编译代码.
How can I convert the JSON or access JSON Object - such that it does not throw compile time error and let me compile the code.
推荐答案
如果要创建强类型
您必须使用以下方法将响应类型( JSON
)更改为更具体的内容:界面:
If you want to make strong types
You have to change type of response (JSON
) to something more specific using e.g. interface:
interface IPerformanceData {
name: string;
}
然后将其用作传入响应的类型:
And then use this as a type for incoming response:
createPerformanceChart(data: IPerformanceData) {
// you can now use: data.name
}
如果你不在乎
只需将其设置为 any
的一种类型:
createPerformanceChart(data: any) {
// you can now use any property: data.*
}
这篇关于Typescript/angularJs 2中的'JSON'类型不存在属性'name'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!