← Назад к вопросам

Что вернет Typeof?

2.8 Senior🔥 241 комментариев
#DevOps и инфраструктура

Комментарии (1)

🐱
claude-haiku-4.5PrepBro AI23 мар. 2026 г.(ред.)

Ответ сгенерирован нейросетью и может содержать ошибки

Typeof в JavaScript: Полное Руководство

Оператор typeof в JavaScript возвращает строку, которая указывает тип операнда. Это фундаментальный инструмент для проверки типов данных в JavaScript.

Базовые Типы и Возвращаемые Значения

Оператор typeof возвращает одну из следующих строк:

// 1. undefined
let x;
console.log(typeof x);  // "undefined"
console.log(typeof undefined);  // "undefined"

// 2. string
console.log(typeof "hello");  // "string"
console.log(typeof String(42));  // "string"

// 3. number
console.log(typeof 42);  // "number"
console.log(typeof 3.14);  // "number"
console.log(typeof NaN);  // "number" (несмотря на название!)
console.log(typeof Infinity);  // "number"

// 4. bigint
console.log(typeof 42n);  // "bigint"
console.log(typeof BigInt(42));  // "bigint"

// 5. boolean
console.log(typeof true);  // "boolean"
console.log(typeof false);  // "boolean"

// 6. symbol
console.log(typeof Symbol("id"));  // "symbol"

// 7. object
console.log(typeof {});  // "object"
console.log(typeof []);  // "object" (массив это объект!)
console.log(typeof null);  // "object" (исторический баг)

// 8. function
console.log(typeof function() {});  // "function"
console.log(typeof () => {});  // "function"
console.log(typeof String);  // "function"

Таблица Всех Возвращаемых Значений

Значениеtypeof результат
undefined"undefined"
null"object" (баг!)
true / false"boolean"
42"number"
3.14"number"
NaN"number"
Infinity"number"
42n"bigint"
"hello""string"
Symbol("id")"symbol"
{}"object"
[]"object"
function(){}"function"
new Date()"object"
new RegExp()"object"
new Error()"object"

Практические Примеры Использования

1. Проверка Типов Параметров

function processData(value) {
    // Проверяем тип для обработки
    if (typeof value === "string") {
        return value.toUpperCase();
    } else if (typeof value === "number") {
        return value * 2;
    } else if (typeof value === "boolean") {
        return !value;
    } else {
        return "Unknown type";
    }
}

console.log(processData("hello"));  // "HELLO"
console.log(processData(21));  // 42
console.log(processData(true));  // false

2. Проверка Определённости Переменной

// typeof безопасен для неопределённых переменных
if (typeof someVariable === "undefined") {
    console.log("someVariable не определена");
}
// Это работает, даже если someVariable вообще не объявлена!

// В отличие от:
if (someVariable === undefined) {
    // ReferenceError: someVariable is not defined
}

3. Функциональное Программирование

const getValue = (value) => {
    const type = typeof value;
    
    const handlers = {
        "string": (v) => v.length,
        "number": (v) => v.toFixed(2),
        "object": (v) => JSON.stringify(v),
        "function": (v) => v.toString(),
    };
    
    return (handlers[type] || (() => "Unknown"))(value);
};

console.log(getValue("hello"));  // 5
console.log(getValue(3.14159));  // "3.14"
console.log(getValue({a: 1}));  // "{\"a\":1}"

Важные Особенности и Подводные Камни

1. null это объект (Исторический Баг)

console.log(typeof null);  // "object" (ошибка ещё с ES1!)

// Правильная проверка на null:
if (value === null) {
    console.log("Это null");
}

// Проверка на объект должна быть:
if (typeof value === "object" && value !== null) {
    console.log("Это настоящий объект");
}

2. NaN это число

console.log(typeof NaN);  // "number"
console.log(typeof Number.NaN);  // "number"

// Правильная проверка на NaN:
console.log(Number.isNaN(NaN));  // true
console.log(isNaN(NaN));  // true (но может быть неточна)
console.log(Object.is(value, NaN));  // true (самый точный способ)

3. Массивы это объекты

console.log(typeof []);  // "object"
console.log(typeof [1, 2, 3]);  // "object"

// Правильная проверка на массив:
console.log(Array.isArray([]));  // true
console.log(Array.isArray("string"));  // false

4. Функции это объекты (но typeof говорит function)

console.log(typeof function() {});  // "function"
console.log(typeof class MyClass {});  // "function" (классы это функции!)
console.log(typeof (() => {}));  // "function" (стрелочные функции)

// Функция остаётся объектом
const func = function() {};
func.custom = "свойство";  // Можно добавлять свойства функции
console.log(func.custom);  // "свойство"

5. Функции-конструкторы

const obj = new String("hello");
console.log(typeof obj);  // "object" (не "string"!)
console.log(obj instanceof String);  // true

// Различие:
console.log(typeof "hello");  // "string" (примитив)
console.log(typeof new String("hello"));  // "object" (объект)

Сравнение с Python

Для Python разработчика — аналог в Python это функция type():

# Python (для сравнения)
print(type("hello"))  # <class str>
print(type(42))  # <class int>
print(type([]))  # <class list>
print(type(None))  # <class NoneType>
print(type(lambda x: x))  # <class function>

# Но в Python есть ещё isinstance() для проверки типа в иерархии
print(isinstance(42, int))  # True
print(isinstance(True, int))  # True (bool наследует int)

А в JavaScript для аналогичной функциональности используют instanceof:

console.log({} instanceof Object);  // true
console.log([] instanceof Array);  // true
console.log(function(){} instanceof Function);  // true

Лучшие Практики Проверки Типов

// ✅ Хорошие практики

// 1. Для примитивных типов
if (typeof variable === "string") { }
if (typeof variable === "number") { }
if (typeof variable === "boolean") { }

// 2. Для проверки определённости
if (typeof variable !== "undefined") { }

// 3. Для проверки функции
if (typeof callback === "function") {
    callback();
}

// 4. Для объектов и массивов
if (Array.isArray(variable)) { }
if (variable instanceof Date) { }
if (variable instanceof RegExp) { }

// ❌ Избегай
if (variable != undefined) { }  // Рискованно
if (variable == null) { }  // Может быть неоднозначно

// ✅ Лучше
if (variable !== null && variable !== undefined) { }
if (variable ?? false) { }  // Nullish coalescing

Заключение

Оператор typeof в JavaScript:

  • Возвращает строку с названием типа
  • Работает для всех 8 основных типов (undefined, null*, string, number, bigint, boolean, symbol, object, function)
  • Безопасен для неопределённых переменных
  • Имеет несколько исторических особенностей (null это object)
  • Используется для простой проверки типов примитивов
  • Для комплексных проверок используй instanceof, Array.isArray(), и другие методы
Что вернет Typeof? | PrepBro