代码之家  ›  专栏  ›  技术社区  ›  dokichan

如何通过TypeScript中的可选对象文件将对象作为函数的参数传递?

  •  0
  • dokichan  · 技术社区  · 3 年前

    假设我的TypeScript API中有一个与数据库通信的函数。

    export const getClientByEmailOrId = async (data: { email: any, id: any }) => {
      return knex(tableName)
        .first()
        .modify((x: any) => {
          if (data.email) x.where('email', data.email)
          else x.where('id', data.id)
        })
    }
    

    在里面 modify 你可以看到我检查传递了什么参数-id或电子邮件。

    在代码中,它是这样的:

    const checkIfEmailUsed = await clientService.getClientByEmailOrId({ email: newEmail })
    

    问题是,我不能这样做,因为缺少参数。但我需要的是,像这样传递它,并检查传递了什么param。

    当然,我可以这么做:

    const checkIfEmailUsed = await clientService.getClientByEmailOrId({ email: newEmail, id: null })
    

    这会起作用的。但有没有解决办法不这样通过: { email: newEmail, id: null } ,但就在旁边 { email: newEmail } ?

    1 回复  |  直到 3 年前
        1
  •  0
  •   Palladium02    3 年前

    我认为您正在寻找可选参数。可以通过添加 ? 到类型声明。

    type Data = {
      email: any,
      id?: any // <= and notice the ? here this makes id optional
    }
    
    export const getClientByEmailOrId = async (data: Data) => {
      return knex(tableName)
        .first()
        .modify((x: any) => {
          if (data.email) x.where('email', data.email)
          else x.where('id', data.id)
        })
    }