TS2345: Argument of type 'X' is not assignable to parameter of type 'Y'
What’s happening?
Section titled “What’s happening?”This error occurs when you pass an argument to a function that doesn’t match the expected parameter type.
Reproduction
Section titled “Reproduction”function greet(name: string) { console.log(`Hello, ${name}!`);}
const userName: string | undefined = getUserName();greet(userName);// ❌ Argument of type 'string | undefined' is not assignable to parameter of type 'string'Solutions
Section titled “Solutions”Option 1: Narrow the type before calling
Section titled “Option 1: Narrow the type before calling”const userName = getUserName();if (userName !== undefined) { greet(userName); // ✅}Option 2: Provide a default value
Section titled “Option 2: Provide a default value”greet(userName ?? "Guest"); // ✅Option 3: Update the function signature
Section titled “Option 3: Update the function signature”function greet(name: string | undefined) { console.log(`Hello, ${name ?? "Guest"}!`);}
greet(userName); // ✅Common scenarios
Section titled “Common scenarios”Passing optional props
Section titled “Passing optional props”function setUserId(id: number) { /* ... */ }
interface Props { userId?: number;}
function Component({ userId }: Props) { setUserId(userId); // ❌ Argument of type 'number | undefined' is not assignable
// ✅ Fix: if (userId !== undefined) { setUserId(userId); }}Key takeaways
Section titled “Key takeaways”- Always check the function signature
- Use type narrowing or defaults before calling
- Consider making function parameters more flexible