首页 > 解决方案 > 打字稿函数接受单个字符串或字符串数​​组

问题描述

下面的函数有 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. 我们还查看了此处建议的REST 参数,但这似乎是不可能的,因为休息参数可以为零或更多,我们至少需要一个。

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

标签: javascripttypescript

解决方案


首先将参数类型从string[]to修改为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}`
    )
  }
}

推荐阅读