admin管理员组文章数量:1389783
The function below takes 2 arguments, a mandatory tableName
and an optional 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}`
)
}
}
Calling this function:
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
In one way or another it should be possible to convert a single string
to an array of strings to be able to use the same logic with array.map
. We've also looked at the REST parameter as suggested here but that seems to be not possible as a rest parameter can be zero or more and we need at least one.
What is the correct way to handle this situation?
The function below takes 2 arguments, a mandatory tableName
and an optional 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}`
)
}
}
Calling this function:
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
In one way or another it should be possible to convert a single string
to an array of strings to be able to use the same logic with array.map
. We've also looked at the REST parameter as suggested here but that seems to be not possible as a rest parameter can be zero or more and we need at least one.
What is the correct way to handle this situation?
Share Improve this question edited Sep 23, 2020 at 8:08 DarkLite1 asked Sep 23, 2020 at 7:47 DarkLite1DarkLite1 14.8k46 gold badges137 silver badges234 bronze badges 8-
3
tableName: string | string[]
? – jonrsharpe Commented Sep 23, 2020 at 7:48 -
But then the
map
function wont work ontablename
liketablename.map()
. – DarkLite1 Commented Sep 23, 2020 at 7:50 -
1
@DarkLite1 Then your function needs to check the
typeof tableName
before deciding if it should be treated like a string or an array of strings. – Terry Commented Sep 23, 2020 at 7:51 -
Of course not, so you need to handle that in the runtime logic too. E.g. use
[tableName]
if it's not already an array. – jonrsharpe Commented Sep 23, 2020 at 7:51 - 4 @jonrsharpe "Of course not" or "How would there be" is not the best expression if you keep in mind that we are at Stackoverflow a place where the questioner does not know everything. Its 100% valid to not have the same knowledge like everybody. Not knowing that typescript is stripped out at runtime can be explained straight without a negative touch. – Jonathan Stellwag Commented Sep 23, 2020 at 8:03
3 Answers
Reset to default 3First modify parameter type from string[]
to string[] | string
and then in try block, when you assign value to promises
, add the type check like so:
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 you want to break down the string | string[] => string[]
problem to one function you can write the following and use it in multiple places:
function convert(param: string | string[]): string[] {
return typeof param === 'string'
? [param]
: param
}
If you want to convert anything to array, try this extension:
declare global {
interface ArrayConstructor {
make<T>(v: T | T[]): T[];
}
}
export function ArrayOf<T = any>(arg: T | T[]): T[] {
return Array.isArray(arg) ? [...arg as T[]] : [...[arg as T]];
}
Array.make = function <T = any>(arg: T | T[]): T[] {
return ArrayOf<T>(arg);
}
本文标签: javascriptTypescript function accept a single string or an array of stringsStack Overflow
版权声明:本文标题:javascript - Typescript function accept a single string or an array of strings - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744606382a2615381.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论