자바스크립트 객체 속성 타입 확인 (Checking Object Property Types)

자바스크립트는 동적 타이핑을 가지는 언어로, 변수들은 런타임에 그 타입이 결정됩니다. 이러한 동적 타이핑으로 인해 객체의 속성들의 타입을 확신하기 어려울 수 있습니다. 하지만 자바스크립트에서는 속성의 타입을 확인하고 검증할 수 있는 다양한 방법들이 제공됩니다.

1. typeof 연산자

typeof 연산자는 피연산자의 타입을 문자열로 반환합니다. 객체의 속성의 타입을 확인하기 위해 이 연산자를 사용할 수 있습니다.

const obj = {
  name: "John",
  age: 25,
  isStudent: true,
  hobbies: ["reading", "coding"]
};

console.log(typeof obj.name); // 출력값: "string"
console.log(typeof obj.age); // 출력값: "number"
console.log(typeof obj.isStudent); // 출력값: "boolean"
console.log(typeof obj.hobbies); // 출력값: "object"

typeof 연산자는 원시 타입 (string, number, boolean, undefined) 에 대해서는 잘 동작하지만, null이나 배열, 객체 등에 대해서는 타입을 정확하게 파악할 수 없는 경우가 있습니다.

2. instanceof 연산자

instanceof 연산자는 객체가 특정 클래스를 상속받았는지를 확인하는 용도로 사용됩니다. 객체의 속성의 타입을 확인하기 위해 instanceof 연산자를 사용할 수 있습니다.

const obj = {
  name: "John",
  age: 25,
  isStudent: true,
  hobbies: ["reading", "coding"]
};

console.log(obj.name instanceof String); // 출력값: true
console.log(obj.age instanceof Number); // 출력값: true
console.log(obj.isStudent instanceof Boolean); // 출력값: true
console.log(obj.hobbies instanceof Array); // 출력값: true

하지만 instanceof 연산자는 Array나 Function 같은 내장 객체의 경우에만 동작하며, 원시 타입 (string, number, boolean, undefined)이나 사용자 정의 객체의 속성의 타입을 정확하게 확인할 수 없는 한계가 있습니다.

3. typeof와 isArray 메서드 조합하기

typeof 연산자와 Array.isArray 메서드를 조합하여 배열과 원시 타입을 구별할 수 있습니다.

const obj = {
  name: "John",
  age: 25,
  isStudent: true,
  hobbies: ["reading", "coding"]
};

console.log(typeof obj.name === "string"); // 출력값: true
console.log(typeof obj.age === "number"); // 출력값: true
console.log(typeof obj.isStudent === "boolean"); // 출력값: true
console.log(Array.isArray(obj.hobbies)); // 출력값: true

위와 같은 방식을 사용하면 배열과 원시 타입에 대한 타입 검증을 더 정확하게 할 수 있습니다.

4. 동적 프로퍼티의 타입 확인하기

위에서 소개한 방법들은 객체의 고정된 프로퍼티 (정적 프로퍼티)에 대한 타입 확인에 유용하지만, 동적으로 추가된 프로퍼티들의 타입은 확인하기 어렵습니다. 이런 경우에는 데이터 속성 디스크립터를 사용하여 타입을 확인할 수 있습니다.

const obj = {
  name: "John",
  age: 25
};

const descriptor = Object.getOwnPropertyDescriptor(obj, 'name');
console.log(descriptor.value); // 출력값: "John"
console.log(descriptor.writable); // 출력값: true
console.log(descriptor.enumerable); // 출력값: true
console.log(descriptor.configurable); // 출력값: true
console.log(typeof descriptor.value); // 출력값: "string"

위와 같이 Object.getOwnPropertyDescriptor 메서드를 사용하여 동적으로 추가된 속성의 타입을 확인할 수 있습니다.

자바스크립트에서 객체의 속성의 타입을 확인하는 것은 코드의 신뢰성을 높이기 위해 중요한 요소입니다. 위에서 소개한 방법들을 적절히 활용하여 객체의 속성들의 타입을 철저히 확인하고, 잘못된 타입이 할당되지 않도록 조심하는 것이 중요합니다.