Ahmer Ali Ahsan
Ahmer Ali Ahsan

Reputation: 6136

In TypeScript, how do I declare a function that returns a string type array?

Possible duplicates:

In TypeScript how do I declare an array of functions that accept a string and return a string?: In this post user talking about return string array from a function using lamda expression.

How to declare Return Types for Functions in TypeScript: In this post, the user is talking about (how I can declare a return type of the function) as mentioned in his post.

Both the above links are not possible duplicates against my question. So let's get started.

What I was expecting in my code: A function that returns a string array, for example, 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');
    }
}

I am getting an error while building my code:

Type 'number' is not assignable to type 'string[]'

Upvotes: 9

Views: 59646

Answers (1)

thitemple
thitemple

Reputation: 6059

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

Upvotes: 23

Related Questions