TypeScript & Typed JSON
TypeScript ensures your code is robust by validating data structures at compile time. Here is the strict Interface definition for our API response to ensure you never access a missing property.
TYPESCRIPT
import axios from 'axios';
// Define the Shape of the API Response
interface TimeResponse {
datetime: string;
unixtime: number;
timezone: string;
utc_offset: string;
dst: boolean;
day_of_year: number;
}
async function fetchTime(zone: string): Promise<void> {
const url = `https://time.now/developer/api/timezone/${zone}`;
try {
// Axios infers the type here
const { data } = await axios.get<TimeResponse>(url);
console.log(`Time in ${data.timezone}: ${data.datetime}`);
console.log(`DST Active: ${data.dst}`);
} catch (err) {
console.error("Failed to sync time");
}
}
fetchTime("America/Toronto");
Why use Time.Now for Backend?
- Strict Type Checking
- IntelliSense Autocomplete
- Prevents runtime errors