Question
How should I represent dates in TypeScript? Since Date does not look like a primitive TypeScript type such as string or number, should I use any or object?
For example, what is the correct way to type this?
let myDate: any = new Date();
I am looking for the proper TypeScript way to express a date value.
Short Answer
By the end of this page, you will understand that the correct way to type a JavaScript date in TypeScript is with the Date type. You will also learn when a value should be a Date object versus a date string or numeric timestamp, how to create and use Date values safely, and which common mistakes to avoid.
Concept
TypeScript uses the same runtime values as JavaScript, but adds static types on top. In JavaScript, dates are represented by the built-in Date class. Because of that, the correct TypeScript type for a date object is also Date.
let myDate: Date = new Date();
You do not need any, and object is too vague. Using Date gives TypeScript useful information:
- the value is a real date object
- methods like
getFullYear()andtoISOString()are available - incorrect assignments can be caught early
For example:
let myDate: Date = new Date();
myDate.getFullYear(); // OK
myDate = "2025-01-01"; // Error
This matters because many programs work with time-based data:
- user account creation dates
- order timestamps
- event scheduling
- logs and analytics
- API responses containing dates
One important detail: a Date object is different from a date string.
let a: Date = new Date();
let b: string = "2025-01-01";
These are not the same type, even if they both represent a date conceptually. A Date is an object with date methods. A string is just text. TypeScript helps you keep that distinction clear.
Mental Model
Think of Date as a specialized tool, like a stopwatch.
- A
stringis like writing a time on paper:"2025-01-01" - A
numbertimestamp is like the raw machine reading behind the stopwatch - A
Dateobject is the actual stopwatch you can operate on
If you want to call methods such as:
getTime()getMonth()toISOString()
then you need the stopwatch itself: a Date.
So the question is not just “does this value describe a date?” but “what kind of date value is this?”
- text date ->
string - Unix timestamp ->
number - JavaScript date object ->
Date
Syntax and Examples
The basic syntax is:
let myDate: Date = new Date();
You can also use Date in function parameters, return types, object properties, and interfaces.
Variable example
let createdAt: Date = new Date();
Function parameter example
function formatDate(date: Date): string {
return date.toISOString();
}
Function return type example
function getCurrentDate(): Date {
return new Date();
}
Object property example
type User = {
name: string;
joinedAt: Date;
};
const user: User = {
name: "Ava",
joinedAt: new Date(),
};
Optional date example
Sometimes a date may be missing.
let deletedAt: Date | null = null;
deletedAt = new Date();
Date string vs Date object
const rawDate: string = "2025-01-01";
const parsedDate: Date = new Date(rawDate);
Here:
rawDateis text from an API, form, or fileparsedDateis a realDateobject
That conversion step is common in real applications.
Step by Step Execution
Consider this example:
const raw = "2025-06-10";
const date: Date = new Date(raw);
const year = date.getFullYear();
console.log(year);
Step by step:
-
rawis created as a string.- Its type is
string - It is not a
Dateyet
- Its type is
-
new Date(raw)creates a JavaScriptDateobject.- TypeScript understands that the result is of type
Date
- TypeScript understands that the result is of type
-
dateis declared asDate.- This matches the value returned by
new Date(raw)
- This matches the value returned by
-
date.getFullYear()is called.- This works because
dateis known to be aDate - TypeScript allows the method call safely
- This works because
-
console.log(year)prints the year.yearis anumber
So the flow is:
- start with a string
- convert it to a
Date - use
Datemethods - get other values such as numbers or strings from it
Real World Use Cases
Dates appear in almost every non-trivial application.
APIs
An API may return timestamps for records:
type ApiPost = {
id: number;
publishedAt: string;
};
After parsing, your app may convert that string into a Date for easier manipulation.
User activity tracking
type Session = {
startedAt: Date;
endedAt: Date | null;
};
This is useful for login sessions, timers, and analytics.
Scheduling
Calendar apps, booking systems, and reminders all work with Date objects to compare times and calculate durations.
Logging and monitoring
type LogEntry = {
message: string;
timestamp: Date;
};
Developers often store or generate dates for audit trails and debugging.
Expiration logic
Dates are used to decide whether something is still valid:
- password reset links
- discount coupons
- authentication tokens
- cached data
Real Codebase Usage
In real codebases, developers usually type date values based on where the data currently is in its lifecycle.
1. Use Date for in-memory date objects
type Order = {
id: string;
createdAt: Date;
};
If your code will call date methods, Date is the right type.
2. Use string for raw API payloads
Many APIs send ISO date strings:
type OrderDto = {
id: string;
createdAt: string;
};
Then map that data into your internal model:
function toOrder(dto: OrderDto): Order {
return {
id: dto.id,
createdAt: new Date(dto.createdAt),
};
}
This separation is very common.
3. Validate before using
A Date object can still be invalid if parsing fails.
const date = new Date("not a real date");
if (Number.isNaN(date.getTime())) {
throw new Error("Invalid date");
}
4. Use nullable or optional dates when needed
type User = {
bannedAt?: Date;
deletedAt: Date | null;
};
This models real application states clearly.
5. Use helper functions for conversion
Large projects often centralize parsing and formatting:
function parseApiDate(value: string): Date {
const date = new Date(value);
if (Number.isNaN(date.getTime())) {
throw new Error("Invalid API date");
}
return date;
}
This avoids scattered date parsing logic across the codebase.
Common Mistakes
Using any
let myDate: any = new Date();
myDate.notARealMethod(); // No type error, but will fail at runtime
Why it is a problem:
- TypeScript cannot protect you
- invalid method calls are allowed
Use this instead:
let myDate: Date = new Date();
Using object
let myDate: object = new Date();
Why it is a problem:
objectis too broad- you cannot safely call date-specific methods
For example:
let myDate: object = new Date();
// myDate.getFullYear(); // Error
Confusing Date with string
let createdAt: Date = "2025-01-01"; // Error
A string that looks like a date is still a string.
Correct approach:
let createdAt: Date = new Date("2025-01-01");
Forgetting that parsed dates can be invalid
const d: Date = new Date("bad input");
console.log(d.getFullYear());
This compiles, but the date may be invalid.
Safer version:
const d: Date = new Date("bad input");
if (Number.isNaN(d.getTime())) {
console.log("Invalid date");
} else {
console.log(d.getFullYear());
}
Typing API date fields as Date too early
If the API returns strings, this is misleading:
type ApiUser = {
createdAt: Date;
};
Better:
type ApiUser = {
createdAt: string;
};
Then convert it after reading the data.
Comparisons
| Concept | TypeScript type | Example value | When to use |
|---|---|---|---|
| Date object | Date | new Date() | When you need date methods and date operations |
| Date text | string | "2025-01-01" | When reading or storing raw textual dates |
| Timestamp | number | 1718000000000 | When working with Unix time or numeric comparisons |
| Unknown value | any | anything | Avoid unless absolutely necessary |
| Generic object | object | new Date() | Too broad for date-specific work |
Date vs string
Datehas methods likegetTime()andtoISOString()stringis just text and must be parsed first
Date vs number
Dateis easier to work with when formatting and extracting partsnumberis useful for timestamps and performance-sensitive comparisons
Date vs any
Dategives type safetyanydisables type checking
In most normal TypeScript code, if the value is a JavaScript date object, the right type is simply Date.
Cheat Sheet
// Correct way to type a date object
let myDate: Date = new Date();
Common patterns
function save(date: Date): void {}
function now(): Date {
return new Date();
}
type Event = {
startsAt: Date;
endsAt: Date | null;
};
Raw API data vs parsed app data
type EventDto = {
startsAt: string;
};
type EventModel = {
startsAt: Date;
};
Convert string to Date
const d: Date = new Date("2025-01-01");
Check for invalid date
const d = new Date(input);
const isInvalid = Number.isNaN(d.getTime());
Rules
- Use
Datefor JavaScript date objects - Use
stringfor raw date text - Use
numberfor timestamps - Avoid
anyunless necessary - Avoid
objectfor date-specific values
Useful methods
date.getFullYear();
date.getMonth();
date.getDate();
date.getTime();
date.toISOString();
FAQ
Is Date a valid type in TypeScript?
Yes. Date is the correct type for JavaScript date objects in TypeScript.
Should I use any for dates in TypeScript?
No. Use Date if the value is a real date object. any removes type safety.
What is the difference between Date and string in TypeScript?
Date is an object with date methods. string is plain text, even if it contains something like "2025-01-01".
How do I type a date from an API response?
Usually as string first, because many APIs send dates as text. Then convert it to Date in your application code.
Can a Date object be invalid even if the type is Date?
Yes. new Date(badValue) still creates a Date object, but it may represent an invalid date. Check with Number.isNaN(date.getTime()).
How do I type an optional date?
Use Date | null or an optional property such as deletedAt?: Date depending on your data model.
Should I use object for a date value?
No. object is too general and does not let TypeScript understand date-specific methods.
Mini Project
Description
Build a small TypeScript example that models blog posts coming from an API. The API returns date values as strings, but your application converts them into Date objects for safe use. This demonstrates the real difference between raw data and typed application data.
Goal
Create a typed conversion flow from API date strings to real Date objects and display formatted information from those dates.
Requirements
- Define one type for the raw API response and one type for the application model.
- Store the API date as a
stringand the application date as aDate. - Write a function that converts the API object into the application object.
- Validate that the parsed date is valid before returning it.
- Print the post title and publication year using the converted
Date.
Keep learning
Related questions
@Directive vs @Component in Angular: Differences, Use Cases, and When to Use Each
Learn the difference between @Directive and @Component in Angular, including use cases, examples, and when to choose each.
Accessing Input Value from EventTarget in TypeScript
Learn why EventTarget has no value property in TypeScript and safely read values from HTML input events in Angular applications.
Angular (change) vs (ngModelChange): What’s the Difference?
Learn the difference between Angular (change) and (ngModelChange), when each fires, and which one to use in forms and inputs.