【问题标题】:Typescript function accept a single string or an array of strings打字稿函数接受单个字符串或字符串数​​组
【发布时间】:2020-09-23 07:47:44
【问题描述】:

下面的函数有 2 个参数,一个强制的tableName 和一个可选的connectionName

export const clearTable = async (
  tableName: string[],
  connectionName = 'default'
) => {
  try {
    const connection = getConnection(connectionName)
    const promises = tableName.map((table) =>
      connection.query(`DELETE FROM ${table}`)
    )
    await Promise.all(promises)
  } catch (error) {
    throw new Error(
      `Failed to clear table '${tableName}' on database '${connectionName}': ${error}`
    )
  }
}

调用这个函数:

clearTable(['table1', 'table2']) // works fine because it receives an array
clearTable('table3') // fails because it's not an array > TypeError: tableName.map is not a function

应该可以通过某种方式将单个string 转换为字符串数组,以便能够使用与array.map 相同的逻辑。我们还按照建议的here 查看了REST parameter,但这似乎是不可能的,因为休息参数可以是零或更多,我们至少需要一个。

处理这种情况的正确方法是什么?

【问题讨论】:

  • tableName: string | string[]?
  • 但是map 函数不会像tablename.map() 一样在tablename 上工作。
  • @DarkLite1 然后你的函数需要检查typeof tableName,然后再决定是否应该将其视为字符串或字符串数​​组。
  • 当然不是,所以你也需要在运行时逻辑中处理它。例如。如果它还不是数组,请使用 [tableName]
  • @jonrsharpe “当然不是”或“怎么会有”不是最好的表达方式,如果您记住,我们在 Stackoverflow 上提问者并不知道一切。 100% 没有像每个人一样拥有相同的知识。不知道 typescript 在运行时被剥离可以直接解释而没有负面影响。

标签: javascript typescript


【解决方案1】:

首先将参数类型从string[]修改为string[] | string,然后在try块中,当你为promises赋值时,添加类型检查,如下所示: Array.isArray(tableName).

export const clearTable = async (
  tableName: string[] | string,
  connectionName = 'default'
) => {
  try {
    const connection = getConnection(connectionName)
    const promises = Array.isArray(tableName) ?
      tableName.map((table) => connection.query(`DELETE FROM ${table}`))
      :
      connection.query(`DELETE FROM ${tableName}`))
    await Promise.all(promises)
  } catch (error) {
    throw new Error(
      `Failed to clear table '${tableName}' on database '${connectionName}': ${error}`
    )
  }
}

【讨论】:

  • 我宁愿先将单个字符串转换为字符串数组。但我会弄清楚的。感谢您的帮助:)
  • 想通了if (typeof tableName === 'string') { tableName = [tableName] }。再次感谢您让我走上正确的道路。
【解决方案2】:

如果您想将string | string[] => string[] 问题分解为一个函数,您可以编写以下代码并在多个地方使用它:

function convert(param: string | string[]): string[] {
  return typeof param === 'string'
    ? [param]
    : param
}

【讨论】:

  • 我喜欢这种模块化的方式,非常方便。谢谢分享:)
猜你喜欢
  • 2016-05-28
  • 1970-01-01
  • 2021-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多