TypeScript Error: Type 'string' is not assignable to type — how to fix?
Hello everyone! I just started learning TypeScript and encountered an unclear error. I have an interface for a user:
```typescript
interface User {
name: string;
age: number;
role: 'admin' | 'user';
}
```
I'm trying to create a user object from data obtained from a form. The data comes as strings (even age is a string from an input). I wrote this code:
```typescript
const formData = {
name: 'Ivan',
age: '25', // string, but should be number
role: 'admin'
};
const user: User = {
name: formData.name,
age: formData.age, // error: Type 'string' is not assignable to type 'number'
role: formData.role // error: Type 'string' is not assignable to type '"admin" | "user"'
};
```
TypeScript complains about age and role. I understand that age should be a number and role should be strictly 'admin' or 'user', but how to correctly convert the types? I tried using `as` — it works, but I heard it's bad practice. Tell me how to properly solve this p
No answers yet.
Log in to leave an answer