2016-05-26 22 views
36

CodiceTypeError: Non deve corrispondere contro 'indefinito' o 'nullo'

client.createPet(pet, (err, {name, breed, age}) => { 
    if (err) { 
    return t.error(err, 'no error') 
    } 
    t.equal(pet, {name, breed, age}, 'should be equivalent') 
}) 

errore

client.createPet(pet, (err, {name, breed, age}) => { 
         ^

TypeError: Cannot match against 'undefined' or 'null'. 

Perche 'si ottengono questo errore? La mia conoscenza dell'ES6 mi ha portato a presumere che questo errore dovrebbe verificarsi solo se l'array o l'oggetto che viene distrutto oi suoi figli è undefined o null.

Non ero a conoscenza del fatto che i parametri di funzione sono utilizzati come corrispondenza. E se lo sono allora perché è solo un errore se provo a distruggere uno di loro? (che non è undefined o null).

risposta

53

this error should only arise if the array or object being destructured or its children is undefined or null .

Esattamente. Nel tuo caso, l'oggetto che viene destrutturato è o undefined o null. Ad esempio,

function test(err, {a, b, c}) { 
    console.log(err, a, b, c); 
} 

test(1, {a: 2, b: 3, c: 4}); 
// 1 2 3 4 
test(1, {}); 
// 1 undefined undefined undefined 
test(1); 
// TypeError: Cannot match against 'undefined' or 'null'. 
+0

Hai ragione, ho fuorviato dalla freccia nel messaggio di errore –

+0

@PrashanthChandra Se si guarda da vicino, la freccia in realtà indica la parentesi di apertura, non errore :-) – thefourtheye

+1

Si tratta di un peccato che una funzionalità rilasciata di recente non contenga un messaggio più informativo e utile – Elad

Problemi correlati