user1679941
user1679941

Reputation:

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

Here's my Typescript class and interface:

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
    }
}

The code fails because this.test is not defined.

How should I define this and should I create a new test object in my constructor? Also is this the correct way for me to declare the interfaces?

I am a bit confused about how properties work in a Typescript class.

Upvotes: 0

Views: 123

Answers (1)

basarat
basarat

Reputation: 276125

If you are looking for a way to initialize an array just use []:

interface ITest {
    qs: ITestQuestion[];
}

interface ITestQuestion {
    answer: string;
}

class QuestionHomeController {

    test: ITest;
    constructor() {

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

should I create a new test object in my constructor?

Your choice.

Also is this the correct way for me to declare the interfaces?

Yes

Update

If there was something like a property called "ready" in my class then how would I declare that with ready: string = null; before my constructor or should I declare: ready: string; and then in the constructor do ready = null

If I already have the value message:string = 'default message'; I do it at the variable declaration. If I need to load it from the server I do it in the constructor.

Update 2

what if you have a property like test with one property you know about and the other qs that gets loaded from the server

I would do the following:

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

Upvotes: 1

Related Questions