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

时间:2016-12-09 10:41:50

标签: class typescript

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

fileone.ts

export class A {
   propertyOne: string;
   propertyTwo: string;
}

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

filetwo.ts

import { A } from './fileone';
export class B {
    myProperty: A;
    mySecondProperty: string;
}

我已经在另一个文件中实例化了这个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);
 }

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

Cannot set the property "propertyOne" of undefined

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

3 个答案:

答案 0 :(得分:6)

您已设置myProperty成员的正确类型,但仅通过声明类型未初始化此变量。因此,您尝试在B实例的propertyOne变量上设置属性undefined

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

export class B {
  myProperty: A;
  constructor() {
    this.myProperty = new A();
  }
}

答案 1 :(得分:3)

myObj.myPropertyA的类型,尚未定义,因此您应该对其进行初始化

myObj.myProperty = new A();

然后使用它

答案 2 :(得分:0)

这似乎超出了范围,但是除了我也使用VueJ之外,我遇到了同样的问题。因此,要摆脱AndreasJägle的回答。这个小变化对我有用,除了我必须添加super();到我的类构造函数。

importmodule.ts

import Vue from 'vue'; 
import { Component, Prop } from 'vue-property-decorator'; 
import { MyProfile } from '../../data';

interface CurrentUser {
    name: string;
    title: string;
    groupName: string; }

@Component 
export default class Profile extends Vue {
    profile: MyProfile;

    constructor() {
        super();
        this.profile = new MyProfile();
    } }

data.ts

export interface IPro {
    name: string;
    title: string;
    groupName: string;
}

export class MyProfile implements IPro {
        name = "User";
        title = "Title";
        groupName = "Group";
    }