TypeError: "x" is (not) "y"
Messaggio
TypeError: "x" is (not) "y" Examples: TypeError: "x" is undefined TypeError: "x" is null TypeError: "undefined" is not an object TypeError: "x" is not an object or null TypeError: "x" is not a symbol
Tipo di errore
Cosa è andato storto?
C'è stato un tipo inaspettato. Questo accade spesso con valori undefined
o null
.
Inoltre, alcuni metodi, come Object.create()
o Symbol.keyFor()
(en-US), richiedono che sia fornito un tipo specifico.
Esempi
Casi non validi
// casi undefined e null in cui il metodo substring non funzionerà
var foo = undefined;
foo.substring(1); // TypeError: foo non è definita
var foo = null;
foo.substring(1); // TypeError: foo è null
// Alcuni metodi potrebbero richiedere un tipo specifico
var foo = {}
Symbol.keyFor(foo); // TypeError: foo non è un simbolo
var foo = 'bar'
Object.create(foo); // TypeError: "foo" non è un oggetto o è null
Risolvere il problema
Per risolvere il problema di valori undefined
o null
, si può usare l'operatore typeof operator, ad esempio.
if (typeof foo !== 'undefined') {
// Ora sappiamo che foo è definita, possiamo procedere.
}