타입

타입 검사 에서 JavaScript

1개의 연습 문제

타입 검사 소개

데이터의 타입이 무엇인지 아는 것은 코드가 매끄럽게, 그리고 오류 없이 실행되는 데 자주 아주 중요해요.

Javascript에는 값이나 객체의 타입을 확인하는 여러 가지 방법이 있어요.

Note

Javascript의 타입 검사 방식은 다소 신뢰할 수 없을 때가 있어요.

더 나은 타입 안정성과 더 강력한 타입을 원한다면, JavaScript를 기반으로 하면서 정적 타입 언어의 타입 문법을 갖춘 TypeScript를 사용하는 게 좋아요.

typeof 연산자

typeof 연산자는 피연산자의 타입을 반환해요. 반환 값은 "null"을 제외하면 원시 데이터 타입 중 하나의 이름과 일치하는 문자열이에요. "function"이나 "object"일 수도 있어요.

typeof undefined;
// => "undefined"

typeof true;
// => "boolean"

typeof 42;
// => "number"

typeof 'Hello, World!';
// => "string"

typeof function () {
  return 'Hello, World';
};
// => "function"

typeof [1, 2, 3, 4];
// => "object"

typeof { city: 'Stockholm', country: 'Sweden' };
// => "object"

이것은 [역사적인 이유][typeof null is "object"] 때문이에요.

instanceof 연산자

객체의 타입을 확인하려면 instanceof 연산자를 사용할 수 있어요. 이 연산자는 두 번째 피연산자가 첫 번째 피연산자의 프로토타입 체인에 포함되는지에 따라 boolean 값으로 평가돼요. 다시 말해, instanceof는 첫 번째 피연산자가 두 번째 피연산자 또는 그 자식 클래스의 인스턴스인지를 반환해요. instanceof는 객체에만 동작해요.

class Beverage {
  // ...
}

// The Coffee class is a child of the Beverage class.
class Coffee extends Beverage {
  // ...
}

const java = new Coffee();

java instanceof Coffee;
// => true

java instanceof Beverage;
// => true
Advanced

Array 클래스에는 인자가 배열인지 확인하는 Array.isArray()라는 메서드가 있어요.

instanceof Array는 웹페이지의 iframe처럼 다른 realm에서 만들어진 배열에는 동작하지 않지만, Array.isArray()는 동작해요.

이는 각 realm마다 Array 클래스의 생성자가 다르고, 각 iframe이 자신만의 realm을 가지기 때문이에요. 그래서 프로토타입 체인의 함수가 달라져 instanceof Array가 실패해요. Array.isArray()는 이 문제를 무시할 수 있어서, 가능하면 항상 사용하는 게 좋아요.

또한 객체가 실제로 Array가 아니라 단지 프로토타입 체인에 Array를 가지고 있을 뿐인 경우의 거짓 양성(false positive)에도 속지 않아요.

({ __proto__: Array.prototype }) instanceof Array
// => true

Array.isArray({ __proto__: Array.prototype })
// => false

in 연산자

in 연산자는 첫 번째 피연산자가 두 번째 피연산자의 속성인지를 반환해요. 속성에 값이 정의되어 있는지는 확인하지 않아요. undefined로 설정된 속성도 in은 여전히 감지해요.

class Coffee {
  constructor() {
    this.temperature = 'hot';
    this.isDarkMatter = undefined;
  }

  coolDown() {
    this.temperature = 'warm';
  }
}

const espresso = new Coffee();

'temperature' in espresso;
// => true

'color' in espresso;
// => false

'isDarkMatter' in espresso;
// => true
Note

in은 상속된 속성과 메서드에 대해서도 true를 반환해요.

"coolDown" in espresso
// => true

"constructor" in espresso
// => true

이를 피하려면 대신 Object.hasOwn()을 사용해요

Object.hasOwn() 함수

Object.hasOwn() 메서드는 지정된 객체가 주어진 속성을 직접 소유하는지(상속받았거나 메서드가 아닌지)를 반환해요.

class Coffee {
  constructor() {
    this.temperature = 'hot';
  }

  coolDown() {
    this.temperature = 'warm';
  }
}
const cappuccino = new Coffee();

Object.hasOwn(cappucino, 'temperature');
// => true

Object.hasOwn(cappucino, 'constructor');
// => false

Object.hasOwn(cappucino, 'coolDown');
// => false
GitHub에서 편집 링크가 새 창이나 탭에서 열려요

타입 검사 배우기