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 || {}
// 값 없어도 에러 안 남
})
'TIL' 카테고리의 다른 글
| node JS 스프레드 연산자에 대해 (1) | 2025.10.13 |
|---|---|
| 서버간 ping 은 동작 안되는데 curl은 되는 경우 (0) | 2025.10.13 |
| DB disk 터질뻔한 후기 (0) | 2025.09.27 |
| BullMQ 사용기 / Redis 클러스터에서 주의할 점 (0) | 2025.09.25 |
| Nginx로 소켓 연결하기 / Upgrade가 필요한 이유 (0) | 2025.09.24 |