EduBw
EduBw

Reputation: 942

Add Objects to Array in function In TypeScript

I have a Object with 12 booleans, I want get only the values true and insert in my ArrayList, but I get error.

let arrayMonths: Array<string> = function () {
    let array: Array<string>;
    let obKeys = Object.keys(this.months), prop: string;

    for (prop of obKeys) {
        if (this.months[prop]) {
            array.push(this.service.months[prop]);
        }
    }
    return array;
}

error:

"message": "The type '() => string []' can not be assigned to the type 'string []'. \ n The 'press' property is missing in the type '() => string []'." ,

Upvotes: 0

Views: 123

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249476

You assign a function to an array, this is not ok. If you want to move the computation of the array to a function and assign the result of the function to the array, you need to execute the function. Also you should use an arrow function if you need to use instance memebrs inside the function (this.months)

let arrayMonths: Array<string> = (() => {
    let array: Array<string> = []; //must initialize 

    for (let month of this.months) { // for - of a simpler option in this case if this.months is string[], you don't provide the definition of this though.
        if (month) {
            array.push(month);
        }
    }
    return array;
})();

Note

If you just want to filter the array Array.filter would be the better option:

let arrayMonths: Array<string> =  this.months.filter(m => !!m);

Upvotes: 1

Related Questions