타입 검사

Created
May 26, 2024 08:08 AM
Tags
2장 타입 다루기

typeof

오른쪽 피 연산자의 타입을 평가하고 문자열로 반환함
typeof 'asd' // 'string' typeof true // 'boolean' typeof undefined // 'undefined'

함정

typeof는 완벽하게 타입을 추론할 수 없다.
이유는 JS의 원시값과 레퍼런스 값 때문.

원시값 (Primitive values)

원시값은 데이터가 단일 값으로 저장되는 데이터 타입.
  1. number: 숫자
  1. string: 문자열
  1. boolean: 참/거짓
  1. null: 값이 없음
  1. undefined: 정의되지 않음
  1. symbol: 고유하고 변경 불가능한 값
  1. bigint: 큰 정수

레퍼런스 값 (Reference values)

레퍼런스 값은 객체와 같은 복합 데이터 타입을 말함.
  1. object: 객체
  1. array: 배열
  1. function: 함수
typeof 는 원시값은 잘 추론하지만 레퍼런스는 잘 추론하지 못한다.
typeof class asd(){} // 'function' typeof function asd(){} // 'function' typeof new String('asd') // 'object' typeof null // 'object'

instanceof

typeof와 비슷하게 사용이 가능한 객체의 prototype chain을 검사하는 연산
function Person(name, age){ this.name = name; this.age = age; } const poco = new Percon('poco', 99); poco instanceof Person // true
function Person(name, age){ this.name = name; this.age = age; } const p = { name: 'poco', age: 99 } const poco = new Percon('poco', 99); p instanceof Person // false

함정

다시 보자면 레퍼런스 값은 다음과 같은게 있음
  1. object: 객체
  1. array: 배열
  1. function: 함수
const arr = [] const f = function (){} const date = new Date() arr instanceof Array // true f instanceof Function // true date instanceof Date // true arr instanceof Object // true f instanceof Object // true date instanceof Object // true
결국 레퍼런스 타입이기 때문에 최상위 객체는 Object
프로토타입 체인을 타고 검사를 하기 때문에 Object를 만나게됨.
그래서 Object 프로토타입 체인을 타고올라가는 특성을 역 이용하는 방법이 있음
Object.prototype.toString.call(new String()) // [object String] Object.prototype.toString.call(arry) // [object Array] Object.prototype.toString.call(new Date()) // [object Date] Object.prototype.toString.call(f) // [object Function]