티스토리 뷰

반응형

 

프로그래밍 언어를 다루면서 타입 검사는 누구나 한 번씩 해보게 되는 과정이다. 아무리 간단한 애플리케이션을 개발한다고 해도 타입 검사는 할 것이다.

 

 

타입 검사의 어려움

typeof는 무적이 아니다

typeof 연산자는 문자열로 해당 타입을 출력해준다.

typeof '문자열' // 'string'
typeof true // 'boolean'
typeof undefined // 'undefined'
typeof 123 // 'number'
typeof Symbol() // 'symbol'

 

 

참조값의 타입

숫자, 문자, boolean, null, undefined, bigInt, Symbol이 원시 값에 해당하며, 이 외에 모든 값은 참조값이다. 참조값은 typeof로 타입을 출력하는 데에 어려움이 있다.

class MyClass {}
typeof MyClass // 'function'

const str = new String('문자열');
typeof str // 'object'

 

class는 'function' 타입으로 출력되며 Wrapper 객체로 원시 값을 생성하게 되면 'object'가 출력된다.

 

Wrapper Object(래퍼 객체)
원시 타입의 값을 감싸는 형태의 객체를 말한다. 
number에 대응하는 Number(), string에 대응하는 String(), boolean에 대응하는 Boolean(), symbol에 대응하는 Symbol()이 있다.

 

 

null에 대한 이슈

typeof null // 'object'

null의 타입은 'object'가 출력된다. 자바스크립트가 인정한 언어적 오류로, 자바스크립트가 계속 발전해오면서 수정을 할 수 없는 상황이라고 판단을 해서 그대로 유지하게 되었다고 한다.

 

 

 

 

instanceof 연산자도 무적이 아니다

객체의 프로토타입 체인을 검사하는 연산자이다.

 

// 생성자 함수
function Person(name, age) {

    this.name = name;
    this.age = age;
    
}

const mike = new Person('mike', 31);
mike instanceof Person; // true

const m = {

    name: 'mike',
    age: 31,
    
};
m instanceof Person; // false

 

이러한 instanceof에도 함정이 있다. 참조 타입의 경우 결국 최상위 프로토타입이 객체이므로 instanceof Object의 출력 값은 무조건 true이다.

 

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

arr instanceof Array; // true
func instanceof Function; // true
date instanceof Date; // true

// 참조 타입은 결국 최상위 프로토타입이 객체이다.
arr instanceof Object; // true
func instanceof Object; // true
date instanceof Object; // true

 

 

보완

참조 타입을 출력할 땐 instanceof 대신 아래와 같은 방법을 사용해보자.

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

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

 

 

 

결론

자바스크립트는 동적으로 변하는 언어이기 때문에 타입도 동적이다. 따라서 타입 검사에 주의해야 한다.

 

 


참고

[Udemy] 클린코드 자바스크립트

반응형
반응형
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31