카테고리 없음

[TypeScript] TS2532: Object is possibly 'undefined' - 원인과 해결방법 완벽 정리

WeVeloper 2025. 12. 23. 11:22
반응형
TypeScript

🔴 TypeScript: Object is possibly 'undefined'

TS2532: Object is possibly 'undefined'

❓ 왜 이 에러가 발생하나요?

Optional 프로퍼티나 nullable 타입을 안전하게 처리하지 않았을 때 발생합니다.

✅ 해결 방법

Optional Chaining, Non-null assertion, 또는 타입 가드를 사용하세요.

💻 코드 예시

// ❌ 에러 발생
interface User {
  name?: string;
}
const user: User = {};
console.log(user.name.toUpperCase()); // Object is possibly 'undefined'

// ✅ 해결 방법 1: Optional Chaining
console.log(user.name?.toUpperCase());

// ✅ 해결 방법 2: Non-null assertion (확실할 때만!)
console.log(user.name!.toUpperCase());

// ✅ 해결 방법 3: 타입 가드
if (user.name) {
  console.log(user.name.toUpperCase());
}
#typescript#undefined
반응형