typeof

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

Der typeof Operator gibt einen String zurück, der den Typ des Werts des Operanden angibt.

Probieren Sie es aus

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

js
typeof operand

Parameter

operand

Ein Ausdruck, der das Objekt oder die Primitive darstellt, dessen Typ zurückgegeben werden soll.

Beschreibung

Die folgende Tabelle fasst die möglichen Rückgabewerte von typeof zusammen. Weitere Informationen zu Typen und Primitiven finden Sie auch auf der Seite JavaScript Datenstrukturen.

Typ Ergebnis
Undefined "undefined"
Null "object" (Grund)
Boolean "boolean"
Number "number"
BigInt "bigint"
String "string"
Symbol "symbol"
Function (implementiert [[Call]] in ECMA-262-Begriffen; Klassen sind ebenfalls Funktionen) "function"
Jedes andere Objekt "object"

Diese Liste von Werten ist vollständig. Es sind keine spec-konformen Engines bekannt, die (oder historisch produziert haben) Werte erzeugen, die nicht in dieser Liste aufgeführt sind.

Beispiele

Grundlegende Verwendung

js
// 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

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

In der ersten Implementierung von JavaScript wurden JavaScript-Werte als Kombination aus einem Typ-Tag und einem Wert dargestellt. Das Typ-Tag für Objekte war 0. null wurde als NULL-Zeiger (0x00 auf den meisten Plattformen) repräsentiert. Folglich hatte null als Typ-Tag 0, daher der typeof Rückgabewert "object". (Referenz)

Ein Fix wurde für ECMAScript vorgeschlagen (über ein Opt-In), aber wurde abgelehnt. Dies hätte zu typeof null === "null" geführt.

Verwendung des new Operators

Alle mit new aufgerufenen Konstruktorfunktionen geben Nicht-Primitiven ("object" oder "function") zurück. Die meisten geben Objekte zurück, mit der bemerkenswerten Ausnahme von Function, die eine Funktion zurückgibt.

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

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

const func = new Function();

typeof func; // "function"

Notwendigkeit von Klammern in der Syntax

Der typeof Operator hat eine höhere Priorität als binäre Operatoren wie Addition (+). Daher sind Klammern erforderlich, um den Typ eines Additionsresultats auszuwerten.

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

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

Interaktion mit nicht deklarierten und nicht initialisierten Variablen

typeof garantiert im Allgemeinen immer, einen String für jeden übergebenen Operanden zurückzugeben. Selbst bei nicht deklarierten Bezeichnern gibt typeof "undefined" zurück, anstatt einen Fehler zu werfen.

js
typeof undeclaredVariable; // "undefined"

Allerdings führt die Verwendung von typeof bei lexikalischen Deklarationen (let const, und class) im gleichen Block vor der Deklarationsstelle zu einem Auftreten eines ReferenceError. Block-skopierte Variablen befinden sich in einer temporalen Toten Zone vom Beginn des Blocks bis zur Verarbeitung der Initialisierung, währenddessen ein Zugriff einen Fehler auslöst.

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

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

Außergewöhnliches Verhalten von document.all

Alle aktuellen Browser stellen ein nicht standardisiertes Host-Objekt document.all mit dem Typ undefined bereit.

js
typeof document.all === "undefined";

Obwohl document.all ebenfalls falsey und lose gleich undefined ist, ist es nicht undefined. Der Fall, dass document.all den Typ "undefined" hat, wird in den Web-Standards als eine "bewusste Verletzung" des ursprünglichen ECMAScript-Standards für die Web-Kompatibilität klassifiziert.

Benutzerdefinierte Methode, die einen spezifischeren Typ erhält

typeof ist sehr nützlich, jedoch nicht so vielseitig, wie es benötigt werden könnte. Zum Beispiel ist typeof [] "object", ebenso wie typeof new Date(), typeof /abc/ usw.

Für eine genauere Typprüfung stellen wir hier eine benutzerdefinierte type(value) Funktion vor, die weitgehend das Verhalten von typeof nachahmt. Für Nicht-Primitiven (d.h. Objekten und Funktionen) gibt sie, wenn möglich, einen spezifischeren Typnamen zurück.

js
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;
}

Um potenziell nicht existierende Variablen zu überprüfen, die sonst einen ReferenceError auslösen würden, verwenden Sie typeof nonExistentVar === "undefined", da dieses Verhalten nicht mit benutzerdefiniertem Code nachgeahmt werden kann.

Spezifikationen

Specification
ECMAScript® 2025 Language Specification
# sec-typeof-operator

Browser-Kompatibilität

Siehe auch