Avatar ·

How to initialize a TypeScript object with data from JSON?

Hello everyone! I just started learning TypeScript and encountered a problem that seems simple, but I can't find an elegant solution.\n\nI have an API that returns JSON with user data. Here's an example of what comes from the server:\n\n```typescript\nconst jsonData = {\n "id": 42,\n "name": "Ivan Petrov",\n "email": "ivan@example.com",\n "isActive": true,\n "createdAt": "2024-03-15T10:30:00Z"\n};\n```\n\nI created an interface for this object:\n\n```typescript\ninterface User {\n id: number;\n name: string;\n email: string;\n isActive: boolean;\n createdAt: Date;\n}\n```\n\nThe problem is that when I try to simply assign JSON to an object of type User:\n\n```typescript\nconst user: User = jsonData; // Error! createdAt is a string, not a Date\n```\n\nTypeScript complains because