假設我在與資料庫通信的 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 })
這就是問題所在,由于缺少引數,我無法做到這一點。但我需要的是像這樣傳遞它,并檢查傳遞了什么引數。
當然,我可以這樣做:
const checkIfEmailUsed = await clientService.getClientByEmailOrId({ email: newEmail, id: null })
這會奏效。但是是否存在不這樣傳遞它的解決方案:{ email: newEmail, id: null },而只是通過{ email: newEmail }?
uj5u.com熱心網友回復:
我認為您正在尋找可選引數。?您可以通過在型別宣告中添加一個來將物件的屬性標記為可選。
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)
})
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/451159.html
標籤:javascript 打字稿
上一篇:角度排序和拆分和陣列
