Signatur
Beschreibung
Der typeof-Operator gibt einen String zurück, der den Typ des Werts des Operanden angibt.
Die folgende Tabelle fasst die möglichen Rückgabewerte von typeof zusammen. Für weitere Informationen zu Typen und primitiven Werten siehe auch die Seite zur JavaScript-Datenstruktur.
- Undefined →
"undefined" - Null →
"object" - Boolean →
"boolean" - Number →
"number" - BigInt →
"bigint" - String →
"string" - Symbol →
"symbol" - Function (implementiert [[Call]] in ECMA-262-Begriffen; classes sind ebenfalls Funktionen) →
"function" - Jedes andere Objekt →
"object"
Diese Werteliste ist erschöpfend. Es sind keine spezifikationskonformen Engines bekannt, die andere Werte als die aufgeführten liefern (oder historisch geliefert hätten).
Parameter
| Name | Typ | Default | Beschreibung |
|---|---|---|---|
| $operand Pflicht | any | — | Ein Ausdruck, der das Objekt oder den primitive Wert repräsentiert, dessen Typ zurückgegeben werden soll. |
Rückgabewert
Beispiele
Grundlegende Verwendung
// 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";
Verwendung des new-Operators
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
// Parentheses can be used for determining the data type of expressions.
const someData = 99;
typeof someData + " foo"; // "number foo"
typeof (someData + " foo"); // "string"
Zusammenspiel mit nicht deklarierten und nicht initialisierten Variablen
typeof undeclaredVariable; // "undefined"
typeof mit lexikalischen Deklarationen (TDZ)
typeof newLetVariable; // ReferenceError
typeof newConstVariable; // ReferenceError
typeof newClass; // ReferenceError
let newLetVariable;
const newConstVariable = "hello";
class newClass {}
Ausnahmeverhalten von document.all
typeof document.all === "undefined";
Benutzerdefinierte Methode für einen spezifischeren Typ
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;
}
// Wichtig · Fallstricke
typeof null: In der ersten Implementierung von JavaScript wurden Werte als Type-Tag und Wert dargestellt. Das Type-Tag für Objekte war 0. null wurde als NULL-Zeiger dargestellt (0x00 auf den meisten Plattformen). Folglich hatte null das Type-Tag 0, weshalb der typeof-Rückgabewert "object" ist. Ein Fix wurde für ECMAScript vorgeschlagen (per Opt-in), aber abgelehnt. Er hätte dazu geführt, dass typeof null === "null".
Konstruktoren mit new: Alle Konstruktorfunktionen, die mit new aufgerufen werden, geben nicht-primitive Werte zurück ("object" oder "function"). Die meisten geben Objekte zurück, mit der bemerkenswerten Ausnahme Function, welches eine Funktion zurückgibt.
Präzedenz: Der typeof-Operator hat eine höhere Präzedenz als binäre Operatoren wie die Addition (+). Daher werden Klammern benötigt, um den Typ eines Additionsergebnisses zu ermitteln.
Nicht deklarierte Variablen: typeof funktioniert mit nicht deklarierten Bezeichnern und gibt "undefined" zurück, anstatt einen Fehler auszulösen. Die Verwendung von typeof auf lexikalischen Deklarationen (let, const, using, await using und class) im gleichen Block vor der Deklarationsstelle löst jedoch einen ReferenceError aus. Block-scoped-Variablen befinden sich vom Beginn des Blocks bis zur Verarbeitung der Initialisierung in einer temporal dead zone, während der beim Zugriff ein Fehler ausgelöst wird.
document.all: Alle aktuellen Browser stellen ein nicht-standardisiertes Host-Objekt document.all mit dem Typ undefined bereit. Obwohl document.all ebenfalls falsy und lose gleich zu undefined ist, ist es nicht undefined. Der Fall, dass document.all den Typ "undefined" hat, ist in den Web-Standards als "willful violation" (vorsätzlicher Verstoß) des ursprünglichen ECMAScript-Standards aus Gründen der Web-Kompatibilität klassifiziert.
Zur Prüfung auf potenziell nicht existierende Variablen, die andernfalls einen ReferenceError auslösen würden, verwenden Sie typeof nonExistentVar === "undefined", da dieses Verhalten nicht mit eigenem Code nachgebildet werden kann.