我试图访问类型记录中嵌套对象的属性(使用了角),但我得到了:对象可能是“未定义的”。这是我写的代码:
export interface adress{
city?: string;
neighborhood?: string;
}
export interface programming{
backend?: string;
frontend?: string;
}
export interface nestedObject{
firstName?: string;
lastName?: string;
completeAdress?: Array<adress>
fullStackKnowledge?: Array<programming>
}
this.exple=[
// first user
{
firstName: 'Msaddak',
lastName: 'Rouabeh',
completeAdress: [
{
city: 'Gafsa',
neighborhood: 'Cité Hached Lalla',
},
{
city: 'Monastir',
neighborhood: 'Skanes',
}
],
fullStackKnowledge: [
{
backend: 'Express js',
frontend: 'Angular',
},
{
backend: 'Spring boot',
frontend: 'React js',
}
]
},
// Second user
{
firstName: 'Houssem',
lastName: 'Ilahi',
completeAdress: [
{
city: 'Tunis',
neighborhood: 'Bardoo',
},
{
city: 'Nabeul',
neighborhood: 'Mrezka',
}
],
fullStackKnowledge: [
{
backend: '.net',
frontend: 'Vue js',
},
{
backend: 'Express js',
frontend: 'React js',
}
]
}
]这是我访问数据的命令:姓氏:{{exple[0].completeAdress[0].city}}</div>
这就是错误: src/app/nested-objectt/nested-objectt.component.html:6:36 - TS2532: Object可能是“未定义的”。
发布于 2022-07-04 10:49:23
使用可选链
{{exple?.[0]?.completeAdress?.[0]?.city}}那个?接线员就像。链式运算符,除了在引用为空(空或未定义)时不引起错误外,表达式短路,返回值为未定义。当与函数调用一起使用时,如果给定函数不存在,则返回未定义的函数。因为在应用程序生命的某个时刻,一些嵌套的属性还不存在。
https://stackoverflow.com/questions/72855515
复制相似问题