Explain
How do I express a date type in TypeScript?
To represent a date in TypeScript, you typically use the Date type from JavaScript. For example:
let myDate: Date = new Date();
This indicates myDate is a Date object rather than just a string. If you need to store or handle date strings instead (e.g., ISO date formats), you’d use string.
1. Declaring a Date Variable
let birthday: Date = new Date("1990-05-23");
- Here,
birthdayis guaranteed to be aDateobject. - You can call methods like
birthday.getFullYear(), etc.
2. Possible Mixed Types
Sometimes you might allow either a Date object or a date string. In that case:
type DateLike = Date | string;
let startDate: DateLike;
startDate = new Date(); // Valid (Date object)
startDate = "2023-05-23"; // Valid (string)
- You must handle each case appropriately in your logic (e.g., type narrowing, checking
typeof).
3. Why Use Date vs. string?
Date: Provides built-in methods (getDate(),toISOString(), etc.) and ensures type safety that it’s a real JS Date instance.string: Good for storing or transmitting date representations (like"YYYY-MM-DD"). But you’ll need to parse/convert it back to aDatefor manipulations.
4. Manipulations & Libraries
- TypeScript doesn’t add new date methods, so you’d still use plain JS or date libraries (e.g., date-fns, Luxon, etc.).
- For instance:
import { format, parseISO } from "date-fns"; const dateObj: Date = parseISO("2023-06-01"); console.log(format(dateObj, "yyyy-MM-dd")); // "2023-06-01"
Also, if you want a deeper understanding of JavaScript fundamentals (which TypeScript builds upon), consider the Grokking JavaScript Fundamentals course by DesignGurus.io. It covers prototypes, closures, async patterns, and more—helping you better utilize JS/TS features, including Date handling.
Recommended Courses