[英]How can I access a class inside another class / TypeScript
I have my main class A我有我的主班A
export class A {
public sourceReference: string;
public charge: Charge;
}
my Charge class looks like such:我的 Charge 类看起来像这样:
export class Charge {
public chargeType: string;
public chargeAccountNumber: string;
public chargeCurrency: string;
}
In my index file I want to use my main class A and populate my payload as follows:在我的索引文件中,我想使用我的主类 A 并按如下方式填充我的有效负载:
import { A } from "./a";
public static create(payload) {
let myData = new A();
myData.sourceReference = payload.sourceRef;
myData.charge.chargeType = payload.type;
myData.charge.chargeAccountNumber = payload.accountNumber;
myData.charge.chargeCurrency = payload.currency
return JSON.stringify(myData)
}
my incoming payload file looks like such:我传入的有效负载文件如下所示:
payload = { sourceRef: "1234", type: '615-01', accountNumber: '123456', currency: 'USD'}
I am able to generate myData.sourceReference我能够生成myData.sourceReference
However,然而,
The problem is that myData.charge
is returning as undefined, resulting in undefined values for myData.charge.chargeType
, myData.charge.chargeAccountNumber
& myData.charge.chargeCurrency
.问题是
myData.charge
返回未定义,导致myData.charge.chargeType
、 myData.charge.chargeAccountNumber
和myData.charge.chargeCurrency
值未定义。
Exception: TypeError: Cannot set property 'chargeType' of undefined异常:TypeError:无法设置未定义的属性“chargeType”
Class A
has a property of the class Charge
.类
A
拥有类的属性Charge
。
Having said that, the charge
property only has a type - but no instance.话虽如此,
charge
属性只有一个类型——但没有实例。
The class A
will have to create an instance of the class Charge
somewhere - mostly in the constructor.类
A
必须在某处创建类Charge
的实例——主要是在构造函数中。
The constructor should look like this:构造函数应如下所示:
export class A {
public sourceReference: string;
public charge: Charge;
constructor() {
this.charge = new Charge()
}
...
The exception is telling you what's the problem.例外是告诉您问题出在哪里。 You have to define myData.charge, using
myData.charge = new Charge()
and then define it's properties like您必须使用
myData.charge = new Charge()
定义 myData.charge,然后定义它的属性,例如
myData.charge.chargeType = payload.type;
myData.charge.chargeAccountNumber = payload.accountNumber;
myData.charge.chargeCurrency = payload.currency
Or if you want to be fancy, you can create a constructor for charge like this:或者,如果你想花哨,你可以像这样创建一个用于充电的构造函数:
export class Charge {
constructor(chargeType:string, chargeAccountNumber:string, chargeCurrency:string){
this.chargeType = chargeType;
this.chargeAccountNumber = chargeAccountNumber;
this.chargeCurrency=chargeCurrency;
}
public chargeType: string;
public chargeAccountNumber: string;
public chargeCurrency: string;
}
And then you can call the constructor like然后你可以像这样调用构造函数
myData.charge = new Charge(chargeType,chargeAccountNumber,chargeCurrency)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.