如何使用类作为typescript中另一个类的属性的类型?

kan*_*san 5 class typescript

我是打字稿的新手.我已经定义了一些类.我已经将它们用作另一个类的属性的类型.例如:

fileone.ts

export class A {
   propertyOne: string;
   propertyTwo: string;
}
Run Code Online (Sandbox Code Playgroud)

现在我在另一个文件中有另一个B类:

filetwo.ts

import { A } from './fileone';
export class B {
    myProperty: A;
    mySecondProperty: string;
}
Run Code Online (Sandbox Code Playgroud)

我已经在另一个文件中实例化了这个B类.我有以下代码:

myapp.ts

import { B } from './filetwo';
export class C {
    let myObj: B = new B();
    myObj.myProperty.propertyOne = 'hello';
    myObj.myProperty.propertyTwo = 'world'';
    console.log(myObj);
 }
Run Code Online (Sandbox Code Playgroud)

现在,当我尝试设置A到B的属性时,它会说出以下错误:

Cannot set the property "propertyOne" of undefined

我们不能像在java中那样做吗?请解释为什么我现在无法做我正在做的事情.对此有什么正确的解决方法.请不要只是给我解决我的问题,但也解释.

And*_*gle 6

您已设置了myProperty成员的正确类型,但仅通过声明类型未初始化此变量.所以你试图在你的B实例propertyOne上的undefined变量上设置一个属性.

如果要正确初始化,则需要在B类中手动执行此操作:

export class B {
  myProperty: A;
  constructor() {
    this.myProperty = new A();
  }
}
Run Code Online (Sandbox Code Playgroud)