How to Fix TypeScript Error TS2345: Argument of Type is Not Assignable

Learn how to understand and fix the TypeScript error TS2345: Argument of type is not assignable. This beginner-friendly guide explains why the error happens and how to resolve it with clear examples.

If you've recently started working with TypeScript, you might have encountered the error TS2345, which says "Argument of type is not assignable to parameter of type." This error can be confusing, especially if you're new to type checking, functions, and interfaces in TypeScript. In this article, we'll explain what this error means, why it happens, and show you simple examples to fix it.

The TS2345 error occurs when you pass an argument to a function or method that doesn't match the expected type declared in the function's parameter. TypeScript uses static type checking to ensure your code is safe, so if you try to send a string where a number is expected, or an object missing required fields, the compiler will raise this error. Understanding TypeScript's type system, including how types, interfaces, and function parameters work, will help you identify and fix these issues more quickly.

typescript
function greet(name: string) {
  console.log('Hello, ' + name);
}

greet(42); // Error: Argument of type 'number' is not assignable to parameter of type 'string'.

To fix TS2345, the key is to make sure the argument type matches the parameter type. In the example above, the function greet expects a string, but a number was passed. To correct it, you should pass a string like greet('Alice'). When working with objects, ensure the object matches the interface or type structure expected. If necessary, use type assertions or update the function's parameter types to accept a broader type like a union type. Also, be mindful of optional parameters and default values to avoid mismatches.

A common mistake causing TS2345 is mixing up types that look similar but have different structures, such as passing an array when an object is required or confusing optional and required properties in interfaces. Another error is ignoring null or undefined types when strict null checking is enabled, leading to assignments that TypeScript will reject. Always check your function signatures, type declarations, and consider using utility types like Partial or Record to help with flexible typing.

In summary, the TypeScript error TS2345 means your argument's type doesn't match the expected parameter type, and this is caught during compile time thanks to TypeScript's static type checking. By understanding parameter types, function signatures, interfaces, and type compatibility, you can easily fix this error by providing matching types or adjusting your types accordingly. This will improve your code reliability and reduce runtime bugs.