TIL

Node.js에서 Partial 쉽게 쓰는 법

하얀잔디 2025. 9. 29. 20:02

TypeScript를 쓰다 보면, 어떤 객체의 일부 속성만 선택적으로 다루고 싶을 때가 많음.

 

이럴 때 Partial<T>를 쓰면 아주 편함!

 

1. Partial이 뭔데?

  • Partial<T> = 제네릭 유틸 타입임
  • 타입 T의 모든 속성을 optional로 바꿔줌
  • 원래는 필수였던 값도 없어도 되게 바뀜
 

2. 예시

 
interface User {
  id: number
  name: string
  email: string
}

 

원래는 이렇게 다 넣어야 함

const user: User = {
  id: 1,
  name: "Alice",
  email: "alice@test.com"
}

 

 

근데 업데이트 API 같은 데서는 email만 필요할 수도 있음
그럴 때 Partial<User> 씀

 

function updateUser(id: number, update: Partial<User>) {
  console.log(update)
}

updateUser(1, { name: "Bob" })              // name만
updateUser(1, { email: "new@test.com" })    // email만
updateUser(1, { name: "Charlie", email: "charlie@test.com" }) // 둘 다

 

 

3. 실무에서 자주 쓰는 경우

(1) DTO 업데이트

 

interface CreateBotParams {
  description: string
  scopes: string[]
  user_id: string
  user_name: string
  create_user_internal_id: number
}

function updateBot(id: string, data: Partial<CreateBotParams>) {
  // 필요한 값만 넣으면 됨
}

(2) req.body 처리할 때

 
app.post("/bots", (req, res) => {
  const {
    description,
    scopes,
    user_id,
    user_name,
    create_user_internal_id,
  }: Partial<CreateBotParams> = req.body || {}

  // 값 없어도 에러 안 남
})