最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Typescript function accept a single string or an array of strings - Stack Overflow

programmeradmin2浏览0评论

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 on tablename like tablename.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
 |  Show 3 more ments

3 Answers 3

Reset to default 3

First 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);
}
发布评论

评论列表(0)

  1. 暂无评论