TypeScript Error: Type 'string | undefined' is not assignable to type 'string' — how to fix?
Hi! I'm new to TypeScript and encountered a confusing error. I have an interface for a user where the `name` field is optional (can be `undefined`). I'm trying to get this name and pass it to a function that only accepts a string, but TypeScript complains.
Here's my code:
```typescript
interface User {
id: number;
name?: string; // optional field
}
function greet(name: string) {
console.log(`Hello, ${name}!`);
}
const user: User = { id: 1, name: 'Anna' };
greet(user.name); // Error: Type 'string | undefined' is not assignable to type 'string'
```
I thought that if the `name` field exists, it's definitely a string. But the compiler says it's `string | undefined`. Why does this happen and how do I properly handle this situation? I tried just ignoring the error with `// @ts-ignore`, but that's bad practice. Please advise how to do it correctly so the code is type-safe? Maybe there are several ways to solve it?
Thanks in advance for your help!
No answers yet.
Log in to leave an answer
Blogs
CI/CD for Rust Projects: Setting Up GitHub Actions
Spring Annotations: @Component, @Repository, @Service — What's the Difference?
Generics in Java: Writing Flexible Code Without (ClassCastException)
*ngFor for objects: how to get keys and values without losing performance