我应该使用new来在typescript类中创建一个对象属性吗?

时间:2014-08-02 08:14:51

标签: javascript typescript

这是我的Typescript类和接口:

interface ITest {
    qs: ITestQuestion[];
    message: string;
}

interface ITestQuestion {
    answer: string;
}

class QuestionHomeController {

    test: ITest = {
        qs: null,
        message: string = "xxxxx"
    }
    constructor() {

        this.test.qs = // << setting to An Array of Test Questions
    }
}

代码失败,因为没有定义this.test。

我应该如何定义它,是否应该在构造函数中创建一个新的测试对象?这也是我申报接口的正确方法吗?

我对属性在Typescript类中的工作方式感到有些困惑。

1 个答案:

答案 0 :(得分:1)

如果您正在寻找初始化阵列的方法,请使用[]

interface ITest {
    qs: ITestQuestion[];
}

interface ITestQuestion {
    answer: string;
}

class QuestionHomeController {

    test: ITest;
    constructor() {

        // initialize test
        this.test =
        {
            qs: [
                { answer: 'first answer' },
                { answer: 'second answer' }
            ]
        };
    }
}
  

我应该在构造函数中创建一个新的测试对象吗?

您的选择。

  

这也是我申报接口的正确方法吗?

<强>更新

  

如果有类似物品叫做&#34;准备就绪&#34;在我的课堂上,我将如何用ready声明:string = null;在我的构造函数之前或者我应该声明:ready:string;然后在构造函数中执行ready = null

如果我已经有值message:string = 'default message';,我会在变量声明中执行此操作。如果我需要从服务器加载它,我在构造函数中执行它。

更新2

  

如果你有一个属性,比如你知道的一个属性和从服务器加载的其他qs

我会做以下事情:

interface ITestQuestion {
    answer: string;
}

interface ITest {
    local: string;
    server: ITestQuestion[];
}

class QuestionHomeController {

    test: ITest = {
        local: 'something',
        server: []
    };
    constructor() {

        // request from server then: 
        this.test.server = [
            { answer: 'first answer' },
            { answer: 'second answer' }
        ];
    }
}