
자바스크립트에서 타입을 검사하는 것은 생각보다 복잡한 작업니다. 각각의 타입 검사 방법과 특징에 대해 알아보자.
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' - 🚨 자바스크립트의 유명한 버그!
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
더 정확한 타입 검사가 필요할 때는 이 방법을 사용
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]'
typeof someVar === 'string'
typeof someVar === 'number'
typeof someVar === 'boolean'
Array.isArray(arr) // 가장 권장되는 방법
// 또는
arr instanceof Array
myObject instanceof MyClass
Object.prototype.toString.call(myVar)
typeof null === 'object'는 자바스크립트의 오래된 버그Object의 인스턴스instanceof는 프로토타입 체인을 확인하므로, 상속 관계에 있는 모든 클래스에 대해 true 반환타입 검사는 상황에 따라 적절한 방법을 선택해야 한다.
typeofinstanceofObject.prototype.toString.call()자바스크립트는 동적 타입 언어다. 때문에 타입 검사가 까다로울 수 있다. 각 상황에 맞는 적절한 타입 검사 방법을 선택하는것이 중요하며, 한 가지 방법만으로는 모든 상황을 커버할 수 없다는 점을 기억하자.