타입 검사

ljjunh·2024년 10월 6일

clean-code-javascript

목록 보기
6/38
post-thumbnail

자바스크립트에서 타입을 검사하는 것은 생각보다 복잡한 작업니다. 각각의 타입 검사 방법과 특징에 대해 알아보자.

1. typeof 연산자 - 기본적인 타입 검사 👶

typeof는 가장 기본적인 타입 검사 연산자로 피연산자를 평가해서 문자열로 반환해준다. 주로 원시(primitive)타입을 검사할 때 유용하다.

// 기본적인 사용법
typeof '문자열'   // 'string'
typeof true      // 'boolean'
typeof undefined // 'undefined'
typeof 123       // 'number'
typeof Symbol()  // 'symbol'

하지만 typeof에는 중요한 한계가 있다. Reference 타입을 정확하게 구분하지 못한다는 점이다.

// Reference 타입에서의 한계
function myFunction() {}
class MyClass {}
const str = new String('문자열')

typeof myFunction // 'function'
typeof MyClass   // 'function' - 클래스도 함수로 인식
typeof str       // 'object' - String 객체는 그냥 object로 표시
typeof null      // 'object' - 🚨 자바스크립트의 유명한 버그!

2. instanceof - 객체의 상속 관계 확인 🔱

instanceof는 객체의 프로토타입 체인을 검사하는 방법을 제공한다. Reference 타입을 더 정확하게 검사할 수 있다.

const arr = []
const func = function() {}
const date = new Date()

// 정확한 타입 체크 가능
arr instanceof Array     // true
func instanceof Function // true
date instanceof Date     // true

하지만 instanceof도 완벽하지 않다. 자바스크립트의 모든 객체는 Object를 상속받기 때문에 다음과 같은 결과가 나온다.

// 모든 객체는 Object의 인스턴스
arr instanceof Object  // true
func instanceof Object // true
date instanceof Object // true

3. Object.prototype.toString.call() - 가장 정확한 타입 검사 🎯

더 정확한 타입 검사가 필요할 때는 이 방법을 사용

const arr = []
const func = function() {}
const date = new Date()

arr instanceof Object // true
func instanceof Object // true
date instanceof Object // true

Object.prototype.toString.call(new String('')) // '[object String]'
Object.prototype.toString.call(arr) // '[object Array]'
Object.prototype.toString.call(func) // '[object Function]'
Object.prototype.toString.call(date) // '[object Date]'

4. 실제 사용시 권장사항 💡

4.1 원시 타입 검사

typeof someVar === 'string'
typeof someVar === 'number'
typeof someVar === 'boolean'

4.2 배열 검사

Array.isArray(arr) // 가장 권장되는 방법
// 또는
arr instanceof Array

4.3 객체의 인스턴스 검사

myObject instanceof MyClass

4.4 정확한 타입 구분이 필요할 때

Object.prototype.toString.call(myVar)

5. 주의사항 ⚠️

  • typeof null === 'object'는 자바스크립트의 오래된 버그
  • 모든 객체는 Object의 인스턴스
  • instanceof는 프로토타입 체인을 확인하므로, 상속 관계에 있는 모든 클래스에 대해 true 반환

정리 📝

타입 검사는 상황에 따라 적절한 방법을 선택해야 한다.

  1. 간단한 원시 타입 검사 → typeof
  2. 객체의 인스턴스 검사 → instanceof
  3. 정확한 타입 확인 필요 → Object.prototype.toString.call()

자바스크립트는 동적 타입 언어다. 때문에 타입 검사가 까다로울 수 있다. 각 상황에 맞는 적절한 타입 검사 방법을 선택하는것이 중요하며, 한 가지 방법만으로는 모든 상황을 커버할 수 없다는 점을 기억하자.

profile
Hello

0개의 댓글