【问题标题】:Accepting a string and a string array as parameters in Typescript在 Typescript 中接受字符串和字符串数组作为参数
【发布时间】:2016-07-18 17:46:53
【问题描述】:

我正在尝试找出解决此问题的最佳方法。我正在将一个库转换为打字稿,并且遇到了一个我以前遇到过的特定问题。有一个函数的定义有点像这样

public execute(path: string | string[]): Promise<Object> {
  if (typeof path == "string") {
    // Turn the string into an array
  }
}

问题是我无法将路径参数转换为数组,因为它的类型为(string | string[])。尝试这样做也失败了。

public execute(path: string | string[]): Promise<Object> {
  newPath: string[];
  if (typeof path == "string") {
    newPath = [path];
  } else {
    newPath = path;
  }
}

因为路径属于(string | string[]) 类型,并且不能分配给string[] 类型。有什么解决办法吗?

【问题讨论】:

  • path: any - 然后进行检查?
  • @tymeJV any 感觉很脏,在输入提示方面没有提供任何帮助

标签: arrays string typescript


【解决方案1】:

其实我只是想通了。如果您使用内置类型转换的 Typescript,则非常简单的解决方案。

public execute(path: string | string[]): Promise<Object> {
  if (typeof path == "string") {
    path = <string[]>[path];
  }
}

然后繁荣!没有错误

【讨论】:

    【解决方案2】:

    您实际上可以在不使用类型断言(强制转换)的情况下使用type guards

    public execute(path: string | string[]): Promise<Object> {
      let newPath: string[];
      if (typeof path === "string") {
        newPath = [path];
      } else {
        newPath = path;
      }
    }
    

    在这个例子中,TypeScript 将 path 的类型从 string | string[] 缩小到 if 块内的 string,所以你不需要类型断言。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-19
      • 1970-01-01
      • 2014-09-14
      • 1970-01-01
      • 2017-08-11
      相关资源
      最近更新 更多