웹개발/자바스크립트

TypeError: Object.hasOwn is not a function 원인과 간단 해결 방법

CodeChef 2025. 1. 22. 13:58
반응형

TypeError: Object.hasOwn is not a function 에러는 JavaScript에서 Object.hasOwn 메서드를 사용할 때 발생합니다. 이 에러는 대개 다음과 같은 이유로 발생합니다:

  1. Node.js 또는 브라우저 환경의 JavaScript 버전 문제
    Object.hasOwn 메서드는 ECMAScript 2022(ES13)에서 추가되었습니다. 따라서 이 메서드를 사용하려면 Node.js 16.9.0 이상 또는 해당 메서드를 지원하는 최신 브라우저 환경이 필요합니다. 

지원 브라우저 확인하기

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn

 

Object.hasOwn() - JavaScript | MDN

The Object.hasOwn() static method returns true if the specified object has the indicated property as its own property. If the property is inherited, or does not exist, the method returns false.

developer.mozilla.org

 


해결 방법

1. Node.js(Backend) 또는 브라우저 업데이트(사용자의 경우)

  • Node.js를 사용하는 경우, Node.js 버전을 확인하고 최신 버전(16.9.0 이상)으로 업데이트하세요.
     
  • 브라우저 환경이라면 최신 브라우저로 업데이트합니다.
node -v # 버전이 낮다면 업데이트: nvm install 16.9.0 nvm use 16.9.0

2. 폴리필 사용

만약 오래된 환경을 유지해야 한다면, Object.prototype.hasOwnProperty를 사용하여 같은 기능을 구현할 수 있습니다.

// 기존 코드
if (Object.hasOwn(obj, key)) {
    console.log("Key exists");
}

// 대체 코드
if (Object.prototype.hasOwnProperty.call(obj, key)) {
    console.log("Key exists");
}

3. 타사 유틸리티 사용

Lodash와 같은 유틸리티 라이브러리에서 제공하는 has 메서드를 사용할 수도 있습니다.

const _ = require('lodash');
if (_.has(obj, key)) {
    console.log("Key exists");
}
 
 

4.  Object.prototype에 추가

node_modules에 설치되어 있는 패키지로 인해 발생하는 경우에는 prototype을 정의하여 해결할 수 있습니다.

if (!Object.hasOwn) {
  Object.hasOwn = function hasOwn(obj: object, prop: PropertyKey): boolean {
    return Object.prototype.hasOwnProperty.call(obj, prop);
  };
}
 
 

원인 정리

이 에러는 실행 환경이 Object.hasOwn 메서드를 지원하지 않을 때 발생합니다. 가장 좋은 해결 방법은 실행 환경을 최신 상태로 유지하거나, 하위 호환성을 고려해 대체 코드를 사용하는 것입니다.

반응형