【问题标题】:In Typescript how do I declare a function that return string type array?在 Typescript 中,如何声明一个返回字符串类型数组的函数?
【发布时间】:2017-06-12 10:31:35
【问题描述】:

可能的重复:

更新说明:

Link1:在这篇文章中,用户谈论使用 lamda 表达式从函数返回字符串数组。

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

我在代码中所期待的,一个返回字符串数组的函数,例如: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[]'

【问题讨论】:

  • string[] 是你输入字符串数组的方式。请为您收到的消息提供minimal reproducible example
  • @jonrsharpe 以上错误是我在构建代码时收到的。
  • @jonrsharpe 请给我一个例子,说明我们如何在 typescript 中声明返回类型为数组的类函数。如果我运行上面的代码,它会显示我描述的错误。

标签: arrays typescript


【解决方案1】:

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

push 方法returns the new length of the array 这就是它试图将数字转换为字符串数组的原因。

那么,你应该做的是:

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

【讨论】:

  • 严重的是我想念什么?男人我无语了。非常感谢。还请告诉我为什么我会被否决?这会影响我的声誉。
  • 我不知道,不是我。
  • @AhmerAliAhsan 猜测一下,因为 “它有点不同” 实际上并没有解释 如何 它是不同的,而你没有实际上包括有助于查明错误的完整回溯。
  • @jonrsharpe 请查看我更新的帖子。现在清了吗?
猜你喜欢
  • 2012-09-24
  • 2012-09-26
  • 1970-01-01
  • 2017-12-09
  • 2021-08-08
  • 2014-12-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多