TypeError
A wrong type error — for example, calling a method on undefined.
Available since: ES3
Syntax
new TypeError(message)Parameters
| Parameter | Type | Description |
|---|---|---|
| message | string | Optional. A description of the error. |
Return value
TypeErrorAn error object.
Examples
The most common error — reading a property of undefined:
const user = undefined;
try {
console.log(user.name);
} catch (error) {
console.log(error.name);
}Output:
TypeErrorA custom TypeError for argument checks:
function double(n) {
if (typeof n !== 'number') {
throw new TypeError(`Expected a number, got ${typeof n}`);
}
return n * 2;
}
try {
double('5');
} catch (error) {
console.log(String(error));
}Output:
TypeError: Expected a number, got stringNotes
Most TypeErrors come from undefined or null where an object was expected. The ?. operator helps: user?.name.
See also
- Error — The base error class: created and thrown with throw.
- ReferenceError — A variable does not exist error.
- Optional chaining (?.) — Safe property access: returns undefined instead of an error if the object is missing.
In the tutorial
- Errors and try...catch — Error handling in JavaScript: try, catch and finally blocks, the error object, the throw statement and built-in error types.