An invalid argument type was provided to a function.
Production Risk
High. This error often points to untested code paths or faulty logic that can cause application crashes. It indicates a clear programming mistake.
This error occurs when a function or method receives an argument of a different data type than it is designed to accept. For example, providing a number where a string is expected will trigger this error. It signals a fundamental mismatch in the contract between the calling code and the function.
- 1A function was called with an incorrect data type for one of its parameters.
- 2A variable was unexpectedly reassigned to a different type before being used in a function call.
- 3Data from an external source, such as a file or API response, was not validated or parsed correctly before use.
This error is thrown during function execution when Node.js performs internal type checking on arguments for its core APIs.
const fs = require('fs');
// The first argument 'path' must be a string, buffer, or URL.
fs.readFile(123, 'utf8', (err, data) => {
if (err) {
console.error(err);
}
});expected output
TypeError [ERR_INVALID_ARG_TYPE]: The 'path' argument must be of type string or an instance of Buffer or URL. Received type number (123)
Fix 1
Correct the Argument Type
WHEN The data type of an argument passed to a function is incorrect.
const fs = require('fs');
// Pass a valid file path as a string.
fs.readFile('./my-file.txt', 'utf8', (err, data) => {
if (err) {
console.error(err);
}
});Why this works
Ensure that all arguments passed to Node.js APIs and other functions match the data types specified in their documentation. Implement type validation in your own functions to provide clear errors.
Fix 2
Validate External Input
WHEN Data is sourced from external inputs like user forms, API responses, or files.
function readFileFromInput(userInput) {
if (typeof userInput.filePath !== 'string') {
throw new TypeError('The provided file path must be a string.');
}
// ... proceed to read file
}Why this works
Before using data from external sources, always validate its type and structure to ensure it conforms to the expected format.
const fs = require('fs');
// The first argument 'path' must be a string, buffer, or URL.
fs.readFile(123, 'utf8', (err, data) => {
if (err) {
console.error(err);
} // this triggers ERR_INVALID_ARG_TYPEtry {
// operation that may throw ERR_INVALID_ARG_TYPE
riskyOperation()
} catch (err) {
if (err.code === 'ERR_INVALID_ARG_TYPE') {
console.error('ERR_INVALID_ARG_TYPE:', err.message)
} else {
throw err
}
}function readFileTypeSafe(path, enc, cb) {
if (typeof path !== 'string') throw new TypeError(`path must be string, got ${typeof path}`)
require('fs').readFile(path, enc, cb)
}✕
✕
https://github.com/nodejs/node/blob/main/lib/internal/errors.js
More information ↗Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev