Avatar ·

How to correctly specify the type for Date in TypeScript? Problems with date types

Hi everyone! I just started learning TypeScript and encountered a problem when working with dates. I have a function that takes a date and returns its formatted string:\n\n```typescript\nfunction formatDate(date: ???) {\n return date.toLocaleDateString('ru-RU');\n}\n```\n\nI can't figure out which type to specify instead of `???`. I tried `string`, but then TypeScript complains that a string doesn't have the `toLocaleDateString` method. I tried `any` — it works, but as I understand, that's bad practice. I also saw in my colleagues' code that they use `Date`, but when trying to pass a string like `"2024-01-15"`, an error occurs.\n\nThe second problem: I get a date from an HTML input (via `document.querySelector('input[type="date"]').value`), and it comes as a string. How do I correctly convert it to the type