JavaScript typeof: verificare il tipo e riconoscere le eccezioni
typeof restituisce una stringa con il tipo, per esempio "number" o "string". null e gli array danno "object", mentre NaN dà "number". Aggiungi verifiche per distinguere questi casi.
Sintassi e stringhe restituite
typeof 42; // "number"
typeof "42"; // "string"
typeof (1 + "2"); // "string"
typeof è un operatore. Le parentesi raggruppano le espressioni. Confronta la stringa con typeof value === "number". Il tipo dipende dal valore corrente. BigInt è un tipo primitivo distinto per gli interi.
Confrontare i valori in un esempio completo
Salva il codice in UTF-8 come typeof-demo.html e aprilo. Lo script confronta i valori e genera una tabella. La funzione freccia è un valore di tipo funzione.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Compare typeof results</title>
</head>
<body>
<h1>Compare typeof results</h1>
<table>
<thead><tr><th>Value</th><th>typeof result</th></tr></thead>
<tbody id="types"></tbody>
</table>
<button id="tdz" type="button">Test let before initialization</button>
<pre id="output"></pre>
<script>
const samples = [
["String", "hello"], ["Number", 42], ["NaN", NaN],
["Infinity", Infinity], ["BigInt", 42n], ["Boolean", true],
["Symbol", Symbol("id")], ["Function", () => {}],
["Array", []], ["null", null], ["Plain object", {}],
["undefined", undefined]
];
const tbody = document.getElementById("types");
for (const [label, value] of samples) {
const row = document.createElement("tr");
for (const text of [label, typeof value]) {
const cell = document.createElement("td");
cell.textContent = text;
row.appendChild(cell);
}
tbody.appendChild(row);
}
const output = document.getElementById("output");
document.getElementById("tdz").addEventListener("click", () => {
try {
const result = typeof later;
let later = 1;
output.textContent = result;
} catch (error) {
output.textContent = error.name;
}
});
</script>
</body>
</html>
NaN, Infinity e i numeri danno number. Array, null e oggetti ordinari danno object, mentre le funzioni danno function. BigInt e Symbol hanno risultati propri. Cambia un valore e ricarica per confrontarlo. Il pulsante Test let before initialization intercetta e mostra il ReferenceError previsto.
Verificare array, null e numeri finiti
const value = [];
Array.isArray(value); // true
value === null; // false
Number.isNaN(NaN); // true
Number.isFinite(12); // true
Number.isFinite("12"); // false
Number.isFinite(Infinity); // false
Usa Array.isArray() per gli array e value === null per null. Number.isFinite() rifiuta NaN e gli infiniti e non converte le stringhe. Se ricevi numeri come testo, verifica il formato e poi il valore convertito.
Nomi non dichiarati e zona morta temporale
typeof neverDeclaredName; // usually "undefined"
{
// typeof waiting; // would throw ReferenceError
let waiting = 1;
console.log(typeof waiting); // "number"
}
Un nome non dichiarato in genere restituisce "undefined". I nomi dichiarati con let, const e class non sono accessibili prima dell’inizializzazione, nella zona morta temporale (TDZ). La riga che fallirebbe è commentata. typeof 1 + "x" produce "numberx" e typeof (1 + "x") produce "string". document.all ha un trattamento speciale per compatibilità.
Verificare le proprietà attese di un oggetto
Esegui il codice nella console. Per controllare un prodotto, escludi null e gli array. Esigi un nome come stringa e un prezzo non negativo che superi Number.isFinite().
{
function isProduct(value) {
return value !== null
&& typeof value === "object"
&& !Array.isArray(value)
&& typeof value.name === "string"
&& Number.isFinite(value.price)
&& value.price >= 0;
}
console.log(isProduct({ name: "Notebook", price: 0 })); // true
console.log(isProduct({ name: "Notebook", price: "12" })); // false
console.log(isProduct({ name: "Notebook", price: NaN })); // false
console.log(isProduct(null)); // false
}
L’output è true, false, false, false. Accetta prezzo 0 e rifiuta la stringa "12" e NaN. L’esempio verifica solo queste proprietà. Se il nome non può essere vuoto, controllane la lunghezza dopo aver rimosso gli spazi iniziali e finali.




