Avatar ·

How to correctly specify the type for Date in TypeScript?

Hi! I just started learning TypeScript after JavaScript and encountered an unclear situation when working with dates.\n\nLet's say I have a function that takes a user's birth date and returns their age:\n\n```typescript\nfunction calculateAge(birthDate) {\n const today = new Date();\n const diff = today.getTime() - birthDate.getTime();\n return Math.floor(diff / (1000 * 60 * 60 * 24 * 365.25));\n}\n```\n\nIn JavaScript, I would just pass `new Date('1990-05-15')` and it would work. But TypeScript complains that the `birthDate` parameter has an implicit type `any`. I tried writing `birthDate: Date`, but then I can't pass a string `'1990-05-15'` or a number `631152000000` (timestamp) — the compiler throws an error.\n\nI also have a user interface:\n\n```typescrip