How to convert a JSON object to a TypeScript class instance?
Hello everyone! I'm new to TypeScript and encountered a problem when working with JSON data. I have a User class with fields and methods:
```typescript
class User {
name: string;
age: number;
email: string;
constructor(name: string, age: number, email: string) {
this.name = name;
this.age = age;
this.email = email;
}
isAdult(): boolean {
return this.age >= 18;
}
}
```
When I receive data from the server in JSON format, for example via fetch:
```typescript
const response = await fetch('/api/user');
const jsonData = await response.json();
// jsonData = { name: 'Ivan', age: 25, email: 'ivan@example.com' }
```
I try to cast it to the User type:
```typescript
const user: User = jsonData as User;
```
But then, when I call the method u
No answers yet.
Log in to leave an answer
Blogs