首页 > 解决方案 > 错误 ReferenceError: countryCallingCode 未定义

问题描述

尝试为countryCallingCode第一个选项中不存在的属性设置值时出现错误。

this.allData.customerFacingPhone.countryCallingCode = newItem.countryCallingCode

我收到错误:

ERROR ReferenceError: countryCallingCode is not defined

当尝试console.log(allData);

我没有customerFacingPhone...我想创建 and 的属性allData customerFacingPhone.countryCallingCode设置值...

标签: javascriptangulartypescript

解决方案


很可能您还没有声明类型。尝试声明如下类型

export SomeComponent {
  allData: {
    customerFacingPhone: {
      countryCallingCode: any; // <-- elegant would be to define correct type here
    }
  } = Object.create(null);     // <-- initializing empty object

  // some example function
  someFunction() {
    this.allData.customerFacingPhone.countryCallingCode = newItem.countryCallingCode;
  }
}

更优雅的方法是使用 TS 接口来定义类型。

数据.ts

export interface Data {
  customerFacingPhone: Phone;
  someOtherProperty: string;
}

export interface Phone {
  countryCallingCode: string;
  someOtherProperty: number;
}

并在控制器中使用

import { Data, Phone } from './data';

export SomeComponent {
  allData: Data = Object.create(null);     // <-- initializing empty object

  // some example function
  someFunction() {
    this.allData.customerFacingPhone.countryCallingCode = newItem.countryCallingCode;
  }
}

推荐阅读