This TypeScript error occurs when you try to pass a null value to a function that expects a string parameter. Caused by strictNullChecks in TypeScript, this error prevents potential runtime errors by catching type mismatches at compile time. The fix involves either explicitly allowing null in the function signature, using null checks before passing arguments, or providing default values.
TypeScript's strictNullChecks feature treats null and undefined as distinct types that must be explicitly handled. When a function parameter is typed as string, TypeScript only allows actual string values to be passed. If your variable might be null, passing it directly to such a function violates TypeScript's type contract. This error is intentional: it forces you to think about what happens when null is encountered, preventing potential runtime errors where code assumes it has a string but actually receives null.
Read the error message carefully to find which argument and which line is causing the issue. Trace back to where the value originates. Common sources include:
- DOM API calls: document.getElementById(), querySelector() return null if not found
- API responses: JSON data with optional fields
- Object properties: values that might be undefined or null
- Function returns: functions that can return null
Add a console.log or use your debugger to confirm the variable is indeed null.
If the function should logically handle null values, update its parameter type to accept null using a union type:
// WRONG - function cannot handle null
function greetUser(name: string): void {
console.log(`Hello, ${name}`);
}
const userName = getUserName(); // might be null
greetUser(userName); // TS2345 error
// CORRECT - function accepts string or null
function greetUser(name: string | null): void {
if (name === null) {
console.log("Hello, anonymous user");
} else {
console.log(`Hello, ${name}`);
}
}
const userName = getUserName(); // might be null
greetUser(userName); // OKIf the function should only receive string values, add a type guard before passing the argument:
function greetUser(name: string): void {
console.log(`Hello, ${name}`);
}
const userName = getUserName(); // might be null
// Check before calling
if (userName !== null) {
greetUser(userName); // OK - TypeScript knows it's a string here
}
// Alternative: use a ternary operator
greetUser(userName ?? "Guest"); // OK - ?? provides a default if nullProvide a default fallback value when the variable is null. The nullish coalescing operator (??) returns the right-hand value only if the left side is null or undefined:
function greetUser(name: string): void {
console.log(`Hello, ${name}`);
}
const userName = getUserName(); // might be null
// Use ?? to provide a default value
greetUser(userName ?? "Guest"); // OK - always passes a string
// This is safer than || because it only replaces null/undefined, not falsy values
const accountName = ""; // empty string
console.log(accountName || "Default"); // outputs "Default" (treats empty string as falsy)
console.log(accountName ?? "Default"); // outputs "" (empty string is not null)When accessing nested properties that might be null, use optional chaining (?.) combined with nullish coalescing:
interface User {
profile?: { name: string };
}
function displayName(name: string): void {
console.log(name);
}
const user: User | null = getUser(); // might be null
// WRONG - multiple errors
displayName(user.profile.name);
// CORRECT - safely extract with fallback
const name = user?.profile?.name ?? "Anonymous";
displayName(name); // OKIf you are absolutely certain a variable is not null (for example, after checking it), use the non-null assertion operator (!) to tell TypeScript to treat it as non-null. Use this sparingly and only when you have confirmed the value cannot be null:
function greetUser(name: string): void {
console.log(`Hello, ${name}`);
}
const userName = getUserName(); // might be null
if (userName !== null) {
// After this check, TypeScript narrows the type automatically
greetUser(userName); // OK - no assertion needed
}
// OR with assertion (less safe, only if you are certain):
const userNameNotNull = userName!; // ! tells TypeScript: trust me, this is not null
greetUser(userNameNotNull); // OKThis error only occurs when strict null checking is enabled. While disabling it would silence the error, it's not recommended because it removes type safety. Instead, embrace the null-safety checks:
{
"compilerOptions": {
"strict": true,
"strictNullChecks": true
}
}Instead of disabling strictNullChecks, properly handle null values in your code using the techniques above. This leads to more reliable applications.
The strict: true option in TypeScript enables strictNullChecks along with several other strict type-checking flags. Null and undefined are intentionally kept as separate types in strict mode to catch potential runtime errors early. When working with DOM APIs, always remember that many return null (getElementById, querySelector, getAttribute). In modern TypeScript, the nullish coalescing operator (??) is preferred over the logical OR operator (||) because || treats all falsy values (0, "", false, NaN) as needing replacement, while ?? only replaces null and undefined. This distinction is crucial: an empty string "" is a valid value and should not be replaced by a default. For complex type scenarios, consider using type guards or type predicates to narrow types safely across conditionals.
Function expression requires a return type
Function expression requires a return type
Value of type 'string | undefined' is not iterable
How to fix "Value is not iterable" in TypeScript
Type 'undefined' is not assignable to type 'string'
How to fix "Type undefined is not assignable to type string" in TypeScript
Type narrowing from typeof check produces 'never'
How to fix "Type narrowing produces never" in TypeScript
Type parameter 'T' has conflicting constraints
How to fix "Type parameter has conflicting constraints" in TypeScript