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

Should I use new to make an object property in a typescript class?

本文关键字:一个对象 创建 属性 new typescript 我应该      更新时间:2023-09-26

下面是我的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
    }
}

代码失败是因为这个。没有定义Test。

我应该如何定义这个,我应该在我的构造函数中创建一个新的测试对象吗?这是我声明接口的正确方式吗?

我对Typescript类中的属性是如何工作的有点困惑

如果你正在寻找一种方法来初始化一个数组,只需使用[]:

interface ITest {
    qs: ITestQuestion[];
}
interface ITestQuestion {
    answer: string;
}
class QuestionHomeController {
    test: ITest;
    constructor() {
        // initialize test
        this.test =
        {
            qs: [
                { answer: 'first answer' },
                { answer: 'second answer' }
            ]
        };
    }
}
我应该在构造函数中创建一个新的测试对象吗?

你的选择。

这也是我声明接口的正确方式吗?

是的

如果在我的类中有一个类似于"ready"的属性,那么我该如何使用ready: string = null;在构造函数之前还是应该声明:ready: string;然后在构造函数中输入do ready = null

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

更新2

如果你有一个属性,比如test,其中一个属性是你知道的,而另一个属性是从服务器加载的

我会这样做:

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' }
        ];
    }
}