【发布时间】: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