Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Typescript how do I declare a function that return string type array?

Possible duplicates:

Updated Description:

Link1 : In this post user talking about return string array from a function using lamda expression.

Link2 : In this post user talking about (how I can declare a return type of the function) as mentioned in his post.

Both above links are not possible duplicates against my this question. So let gets started.

What I was expecting in my code, A function that returns string array For Ex : public _citiesData: string[];

I have a TypeScript class definition that starts like this:

export class AppStartupData {
public _citiesData: string[];

constructor() {
    this.citiesData();
}

    citiesData():string[] {
        return this._citiesData.push('18-HAZARI','A.K','ABBOTABAD');
    }
}

Getting Error while building my code

 Type 'number' is not assignable to type 'string[]'
like image 926
Ahmer Ali Ahsan Avatar asked Dec 14 '22 01:12

Ahmer Ali Ahsan


1 Answers

Your error is because you're returning the value of the push method.

The push method returns the new length of the array and that's why it's trying to convert a number to an array of strings.

So, what you should do is this:

citiesData():string[] {
    this._citiesData.push('18-HAZARI','A.K','ABBOTABAD');
    return this._citiesData;
}
like image 180
thitemple Avatar answered May 23 '23 09:05

thitemple