typeof

typeof

typeof 연산자는 피연산자 값의 타입을 나타내는 문자열을 반환합니다. Baseline Widely available — 2015년 7월부터 여러 브라우저에서 지원되는 잘 정착된 기능입니다.

출처: typeof

본문

typeof 연산자는 피연산자 값의 타입을 나타내는 문자열을 반환합니다.

시도해 보기 (Try it)

console.log(typeof 42);
// Expected output: "number"

console.log(typeof "blubber");
// Expected output: "string"

console.log(typeof true);
// Expected output: "boolean"

console.log(typeof undeclaredVariable);
// Expected output: "undefined"

구문 (Syntax)

typeof operand

매개변수 (Parameters)

  • operand: 타입이 반환될 객체 또는 원시 값을 나타내는 표현식입니다.

설명 (Description)

다음 표는 typeof의 가능한 반환값들을 요약합니다. 타입과 원시 값에 대한 자세한 내용은 JavaScript 데이터 구조 페이지를 참고하세요.

타입 결과
Undefined "undefined"
Null "object" (이유 참고)
Boolean "boolean"
Number "number"
BigInt "bigint"
String "string"
Symbol "symbol"
Function (ECMA-262 용어로 [[Call]]을 구현; 클래스도 함수) "function"
그 외의 다른 객체 "object"

이 값 목록은 완전합니다. 명세를 준수하는 엔진이 위에 나열된 값 이외의 값을 생성한(또는 역사적으로 생성한) 보고는 없습니다.

예제 (Examples)

기본 사용법

// Numbers
typeof 37 === "number";
typeof 3.14 === "number";
typeof 42 === "number";
typeof Math.LN2 === "number";
typeof Infinity === "number";
typeof NaN === "number"; // Despite being "Not-A-Number"
typeof Number("1") === "number"; // Number tries to parse things into numbers
typeof Number("shoe") === "number"; // including values that cannot be type coerced to a number

typeof 42n === "bigint";

// Strings
typeof "" === "string";
typeof "bla" === "string";
typeof `template literal` === "string";
typeof "1" === "string"; // note that a number within a string is still typeof string
typeof typeof 1 === "string"; // typeof always returns a string
typeof String(1) === "string"; // String converts anything into a string, safer than toString

// Booleans
typeof true === "boolean";
typeof false === "boolean";
typeof Boolean(1) === "boolean"; // Boolean() will convert values based on if they're truthy or falsy
typeof !!1 === "boolean"; // two calls of the ! (logical NOT) operator are equivalent to Boolean()

// Symbols
typeof Symbol() === "symbol";
typeof Symbol("foo") === "symbol";
typeof Symbol.iterator === "symbol";

// Undefined
typeof undefined === "undefined";
typeof declaredButUndefinedVariable === "undefined";
typeof undeclaredVariable === "undefined";

// Objects
typeof { a: 1 } === "object";

// use Array.isArray or Object.prototype.toString.call
// to differentiate regular objects from arrays
typeof [1, 2, 4] === "object";

typeof new Date() === "object";
typeof /regex/ === "object";

// The following are confusing, dangerous, and wasteful. Avoid them.
typeof new Boolean(true) === "object";
typeof new Number(1) === "object";
typeof new String("abc") === "object";

// Functions
typeof function () {} === "function";
typeof class C {} === "function";
typeof Math.sin === "function";

typeof null

// This stands since the beginning of JavaScript
typeof null === "object";

JavaScript의 첫 번째 구현에서는 JavaScript 값이 타입 태그(type tag)와 값으로 표현되었습니다. 객체의 타입 태그는 0이었습니다. null은 NULL 포인터(대부분의 플랫폼에서 0x00)로 표현되었습니다. 결과적으로 null은 타입 태그가 0이었고, 따라서 typeof 반환값이 "object"가 되었습니다. (참조)

ECMAScript에 수정이 제안되었지만(옵트인 방식으로) 거부되었습니다. 그것이 채택되었다면 typeof null === "null"이 되었을 것입니다.

new 연산자 사용하기

new로 호출된 모든 생성자 함수는 비원시 값("object" 또는 "function")을 반환합니다. 대부분 객체를 반환하지만, 주목할 만한 예외로 Function은 함수를 반환합니다.

const str = new String("String");
const num = new Number(100);

typeof str; // "object"
typeof num; // "object"

const func = new Function();

typeof func; // "function"

구문에서 괄호의 필요성

typeof 연산자는 덧셈(+) 같은 이항 연산자보다 우선순위가 높습니다. 따라서 덧셈 결과의 타입을 평가하려면 괄호가 필요합니다.

// Parentheses can be used for determining the data type of expressions.
const someData = 99;

typeof someData + " foo"; // "number foo"
typeof (someData + " foo"); // "string"

선언되지 않은 변수와 초기화되지 않은 변수와의 상호작용

typeof는 선언되지 않은 식별자에서도 동작하며, 오류를 던지는 대신 "undefined"를 반환합니다.

typeof undeclaredVariable; // "undefined"

그러나 어휘 선언(let, const, using, await using, class)에 대해 같은 블록 안에서 선언 위치보다 앞에서 typeof를 사용하면 ReferenceError가 발생합니다. 블록 스코프 변수는 블록 시작부터 초기화가 처리될 때까지 시간적 사각지대(temporal dead zone)에 있으며, 그동안 접근하면 오류가 발생합니다.

typeof newLetVariable; // ReferenceError
typeof newConstVariable; // ReferenceError
typeof newClass; // ReferenceError

let newLetVariable;
const newConstVariable = "hello";
class newClass {}

자세한 내용은 typeof 연산자와 undefined 문서를 참고하세요.

document.all의 예외적 동작

모든 현재 브라우저는 타입이 undefined인 비표준 호스트 객체 document.all을 노출합니다.

typeof document.all === "undefined";

document.all은 또한 falsy이고 undefined와 느슨하게 동등(loosely equal)하지만, 실제로 undefined는 아닙니다. document.all"undefined" 타입을 갖는 경우는 웹 표준에서 웹 호환성을 위한 원래 ECMAScript 표준의 "고의적 위반(willful violation)"으로 분류됩니다.

더 구체적인 타입을 얻는 사용자 정의 메서드

typeof는 매우 유용하지만, 요구사항만큼 다재다능하지는 않습니다. 예를 들어 typeof []"object"인데, typeof new Date(), typeof /abc/ 등도 마찬가지입니다.

타입 검사의 특수성을 높이기 위해, 여기서는 typeof의 동작을 대부분 모방하지만 비원시 값(즉 객체와 함수)에 대해서는 가능한 한 더 세분화된 타입 이름을 반환하는 사용자 정의 type(value) 함수를 제시합니다.

function type(value) {
  if (value === null) {
    return "null";
  }
  const baseType = typeof value;
  // Primitive types
  if (!["object", "function"].includes(baseType)) {
    return baseType;
  }

  // Symbol.toStringTag often specifies the "display name" of the
  // object's class. It's used in Object.prototype.toString().
  const tag = value[Symbol.toStringTag];
  if (typeof tag === "string") {
    return tag;
  }

  // If it's a function whose source code starts with the "class" keyword
  if (
    baseType === "function" &&
    Function.prototype.toString.call(value).startsWith("class")
  ) {
    return "class";
  }

  // The name of the constructor; for example `Array`, `GeneratorFunction`,
  // `Number`, `String`, `Boolean` or `MyCustomClass`
  const className = value.constructor.name;
  if (typeof className === "string" && className !== "") {
    return className;
  }

  // At this point there's no robust way to get the type of value,
  // so we use the base implementation.
  return baseType;
}

그렇지 않으면 ReferenceError를 발생시킬 수 있는 잠재적으로 존재하지 않는 변수를 검사하려면 typeof nonExistentVar === "undefined"를 사용하세요. 이 동작은 사용자 정의 코드로는 흉내 낼 수 없기 때문입니다.

명세 (Specifications)

typeof 연산자는 ECMAScript 언어 명세에 정의되어 있습니다.

브라우저 호환성 (Browser compatibility)

이 기능은 대부분의 현대 브라우저에서 널리 지원됩니다(Baseline Widely available). 자세한 호환성 표는 MDN의 브라우저 호환성 섹션을 참고하세요.

더 알아보기