动态

详情 返回 返回

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.