在 Typescript 中,如何声明一个返回字符串类型数组的函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41882174/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In Typescript how do I declare a function that return string type array?
提问by Ahmer Ali Ahsan
Possible duplicates:
可能的重复:
Updated Description:
更新说明:
Link1: In this post user talking about return string array from a function using lamda expression.
Link1:在这篇文章中,用户谈论使用 lamda 表达式从函数返回字符串数组。
Link2: In this post user talking about (how I can declare a return type of the function) as mentioned in his post.
Link2:在这篇文章中,用户谈论(我如何声明函数的返回类型),正如他的文章中提到的。
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[];
我在我的代码中期望的是一个返回字符串数组 For Ex 的函数: public _citiesData: string[];
I have a TypeScript class definition that starts like this:
我有一个像这样开始的 TypeScript 类定义:
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[]'
回答by thitemple
Your error is because you're returning the value of the push method.
您的错误是因为您返回了 push 方法的值。
The push method returns the new length of the arrayand that's why it's trying to convert a number to an array of strings.
push 方法返回数组的新长度,这就是它尝试将数字转换为字符串数组的原因。
So, what you should do is this:
所以,你应该做的是:
citiesData():string[] {
this._citiesData.push('18-HAZARI','A.K','ABBOTABAD');
return this._citiesData;
}