javascript - 打字稿函数接受单个字符串或字符串数组
问题描述
下面的函数有 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 参数,但这似乎是不可能的,因为休息参数可以为零或更多,我们至少需要一个。
处理这种情况的正确方法是什么?
解决方案
首先将参数类型从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}`
)
}
}
推荐阅读
- flutter - 谁能告诉我如何解决这个问题,因为我已经尝试了所有现有的解决方案
- javascript - 服务器向多个客户端发送事件 - 仅向每个客户端发送相关事件
- sql - 使用反映表值的列名创建 SQL 结果集
- docker - 构建Docker镜像时--no-cache和--rm有什么区别
- outlook - 通过 EWS 在委托日历上创建的事件对委托用户不可见
- azure - 使用 API 通过 Azure 数据工厂刷新 PowerBI
- javascript - 为什么当我 console.log 这个函数时我一直不确定
- yaml - 如何在 Lquid 或 Javascript 中循环遍历 YAML 集合和 110 中的子集合?
- machine-learning - 我已经使用具有 21 个类的数据集执行了 XGBoost 模型,因此应用了以下代码
- python - 无法让 python 脚本在 Power BI 中工作