在Typescript中如何声明一个返回字符串类型数组的函数?

时间:2017-01-26 20:15:18

标签: arrays typescript

可能重复:

更新说明:

Link1:在这篇帖子中,用户使用lamda表达式讨论返回字符串数组。

Link2:在这篇帖子中,用户正在谈论(我如何声明函数的返回类型),如他的帖子所述。

以上两个链接都不可能与我的问题重复。所以让我们开始吧。

我在代码中期待的是一个返回字符串数组的函数Ex:public _citiesData: string[];

我有一个类似于以下内容的TypeScript类定义:

export class AppStartupData {
public _citiesData: string[];

constructor() {
    this.citiesData();
}

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

在构建代码时出错

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

1 个答案:

答案 0 :(得分:6)

您的错误是因为您返回了push方法的值。

推送方法returns the new length of the array,这就是为什么它试图将数字转换为字符串数组。

那么,你应该做的是:

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