Javascript

[JS] JavaScript의 타입 검사

Alexim 2022. 5. 29. 01:06

JavaScript에서 타입을 검사하는 건 쉽지 않습니다. 동적인 언어라서 타입도 동적으로 변할 수 있기 때문입니다.

타입을 검사할 때는 하나의 방법만 사용하지 않고 상황에 맞는 타입 검사 방법을 선택해야합니다.

타입을 검사하는 방법 중 typeof, instanceof, Object.prototype.toString, Array.isArray 4가지를 알아보도록 하겠습니다.

 

1. typeof

typeof는 타입을 문자열로 반환합니다. 함수처럼도 사용 가능합니다.

function myFunction() {};
typeof myFunction; // 'function'
class MyClass {}
typeof MyClass; // 'function' class도 function으로 나온다.

// wrapper 객체
new str = new String('문자열');
typeof str // 'object'

typeof의 문제점

  • typeof는 Primitive(원시형)의 경우에는 타입 검사가 잘 작동하지만 Reference(참조형)의 경우에는 감별 오류가 발생합니다.
  • 가장 치명적인 문제점 중에 하나는 null입니다.
typeof null

결과 : 'object'

결과가 object로 나옵니다. 이 문제는 자바스크립트에서 오류가 "맞다" 라고 인정한 부분입니다. 수정할 수 없다고 판단하였다고 하네요.

 

2. instanceof

instanceof는 typeof와 비슷하게 사용할 수 있는 연산자입니다. 

mdn 설명 :  "instanceof 연산자는 생성자의 prototype 속성이 객체의 프로토타입 체인 어딘가 존재하는지 판별합니다."

피연산자인 객체가 우항에 명시한 타입(constructor)의 인스턴스인지 여부를 알려줍니다.

function Person(name, age) {
  this.name = name;
  this.age = age;
}

const p = {
  name: 'hyunjung',
  age: 99,
}

const hyunjung = new Person('hyunjung', 99);

p instanceof Person // false
hyunjung instanceof Person // true
const arr = [];
const func = function() {};
const date = new Date();
const string = new String("string");

arr instanceof Array // true
func instanceof Function // true
date instanceof Date // true
string instanceof String // true

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

위 typeof 방법에서 wrapper 객체가 'object'로 나왔던 것과는 달리 instanceof에서는 String으로 잘 확인이됩니다.

 

instanceof의 문제점

프로토타입에 constructor.prototype이 존재하는지 확인하는 것이기 때문에 최상단 Object를 입력해도 true가 나옵니다.

 

3. Object.prototype.toString

객체를 나타내는 문자열을 반환합니다.

Object.prototype.toString.call('');             // [object String]
Object.prototype.toString.call(new String());   // [object String]
Object.prototype.toString.call(1);              // [object Number]
Object.prototype.toString.call(new Number());   // [object Number]
Object.prototype.toString.call(NaN);            // [object Number]
Object.prototype.toString.call(Infinity);       // [object Number]
Object.prototype.toString.call(true);           // [object Boolean]
Object.prototype.toString.call(undefined);      // [object Undefined]
Object.prototype.toString.call();               // [object Undefined]
Object.prototype.toString.call(null);           // [object Null]
Object.prototype.toString.call([]);             // [object Array]
Object.prototype.toString.call({});             // [object Object]
Object.prototype.toString.call(new Date());     // [object Date]
Object.prototype.toString.call(Math);           // [object Math]
Object.prototype.toString.call(/test/i);        // [object RegExp]
Object.prototype.toString.call(function () {}); // [object Function]
Object.prototype.toString.call(document);       // [object HTMLDocument]
Object.prototype.toString.call(argument);       // [object Arguments]
Object.prototype.toString.call(undeclared);     // ReferenceError
function getType(target) {
  return Object.prototype.toString.call(target).slice(8, -1);
}

타입을 반환하는 함수를 만들어 사용할 수도 있습니다. 

getType('');         // String
getType(1);          // Number
getType(true);       // Boolean
getType(undefined);  // Undefined
getType(null);       // Null
getType({});         // Object
getType([]);         // Array
getType(/test/i);    // RegExp
getType(Math);       // Math
getType(new Date()); // Date
getType(function () {}); // Function

 

4. Array.isArray

배열인지 체크하기 위해서 사용할 수 있습니다. 

console.log(Array.isArray([]));    // true
console.log(Array.isArray({}));    // false
console.log(Array.isArray('123')); // false

 

 

참고 및 출처

https://poiemaweb.com/js-type-check

 

Type Checking | PoiemaWeb

자바스크립트는 동적 타입(dynamic typed) 언어이므로 변수에 어떤 값이 할당될 지 예측하기 어렵다. 아래 코드를 살펴보자.

poiemaweb.com

https://www.udemy.com/course/clean-code-js/

 

클린코드 자바스크립트

자바스크립트를 위한 코드 스타일부터 습관 그리고 클린 코드에 대해 함께 고민해보고 그 이유에 대해 탐구하고 또 학습해보는 시간을 가집니다.

www.udemy.com