動態

詳情 返回 返回

TypeScript新增接口和更新接口傳參定義差異的問題 - 動態 詳情

interface User {
    id?: string;
    name: string;
    age: number;
}

// 新增用户時,id不是必須的,name和age必須,如何給data定義呢?
export const addUser = (data: User) => fetch('/api/user/add', {
  method: 'POST',
  body: JSON.stringify(data)
})

// 更新用户時,id是必須的,name和age非必須,如何給data定義呢?
export const updateUser = (data: User) => fetch('/api/user/update', {
  method: 'POST',
  body: JSON.stringify(data)
})

方案1:分別定義

interface AddUser {
    name: string;
    age: number;
}

interface UpdateUser {
    id: string;
    name?: string;
    age?: number;
}

const addUser = (data: AddUser) => fetch('/api/user/add', {
  method: 'POST',
  body: JSON.stringify(data)
})

const updateUser = (data: UpdateUser) => fetch('/api/user/update', {
  method: 'POST',
  body: JSON.stringify(data)
})

方案2:使用Partial

interface AddUser {
    name: string;
    age: number;
}

type UpdateUser = {
  id: string;
} & Partial<AddUser>;
// Partial讓AddUser的所有屬性都變成可選的

const addUser = (data: AddUser) => fetch('/api/user/add', {
  method: 'POST',
  body: JSON.stringify(data)
})

const updateUser = (data: UpdateUser) => fetch('/api/user/update', {
  method: 'POST',
  body: JSON.stringify(data)
})
user avatar freeman_tian 頭像 xiaolei_599661330c0cb 頭像 bugDiDiDi 頭像 licin 頭像 lovecola 頭像 gomi 頭像 yanyue404 頭像 dirackeeko 頭像 ichu 頭像 kk_470661 頭像 nidexiaoxiongruantangna 頭像 opentiny 頭像
點贊 55 用戶, 點贊了這篇動態!
點贊

Add a new 評論

Some HTML is okay.