How to convert JSON object to TypeScript class instance?
Hi everyone! I'm new to TypeScript and encountered a problem when working with JSON data. I have a User class that contains fields and methods:
```typescript
class User {
constructor(
public id: number,
public name: string,
public email: string,
public createdAt: Date
) {}
getDisplayName(): string {
return `${this.name} (${this.email})`;
}
}
```
I receive data from an API in JSON format:
```typescript
const jsonData = '{"id": 1, "name": "Ivan", "email": "ivan@example.com", "createdAt": "2024-01-15T10:30:00Z"}';
const parsedData = JSON.parse(jsonData);
```
When I try to use parsedData as a User instance, I cannot call the getDisplayName() method because TypeScript does not create a real class object. parsedData is just a
No answers yet.
Log in to leave an answer