/
example.ts
74 lines (62 loc) · 2.8 KB
/
example.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import { fetchWeatherData } from './main'
async function example1() {
console.log('\nexample 1\n=========')
// type of data is inferred from type of given weather data params
const data = await fetchWeatherData({
latitude: 49.0699764,
longitude: 11.614277,
timezone: 'Europe/Berlin',
forecast_days: 3,
hourly: ['temperature_2m', 'rain' /* 'cloud_cover' */],
daily: ['temperature_2m_max'],
})
// only requested params can be accessed and are suggested by autocompletion
const rain0 = data.hourly.rain[0]
const firstHour = data.hourly.time[0] // time is always present if at least one variable was requested
// const cover = data.hourly.cloud_cover[0] // TS Error: Property 'cloud_cover' does not exist on type 'TimeSeries<"temperature_2m" | "rain">'
const tempMax = data.daily.temperature_2m_max[0] // typescript error
// const currentTemp = data.current.temperature_2m[0] // TS Error: Property 'temperature_2m' does not exist on type never
console.log({ rain0, firstHour: new Date(firstHour * 1000), tempMax })
}
// type inference also works if you construct the params if you use "as const"
async function example2() {
console.log('\nExample 2\n=========')
const hourly = ['temperature_2m'] as const // as const is necessary to infer the type later
const params = {
latitude: 49.0699764,
longitude: 11.614277,
timezone: 'Europe/Berlin',
forecast_days: 3,
hourly,
current: ['wind_speed_10m'],
} as const
const data = await fetchWeatherData(params)
const temperature = data.hourly.temperature_2m
// const err = data.hourly.cloud_cover_high[0] // type error
const current_wind_speed = data.current.wind_speed_10m
console.log({ temperature, current_wind_speed })
}
async function example3() {
console.log('\nExample 3\n=========')
const params = {
latitude: 49.0699764,
longitude: 11.614277,
timezone: 'Europe/Berlin',
forecast_days: 3,
daily: ['sunshine_duration', 'sunrise', 'sunset'],
} as const
const data = await fetchWeatherData(params)
// durations and timestamps are stored in seconds
// timestamps are always UTC
// to convert a timestamp a Date object we need to multiply it with 1000 first
// and add utc_offset_seconds if we want to convert it to an UTC timestamp
const { time, sunshine_duration, sunrise, sunset } = data.daily
const localTime = (ts: number) =>
new Date((ts + data.utc_offset_seconds) * 1000).toISOString().substring(0, 19).replace('T', ' ')
console.log('sunshine duration in hours:', Math.round(sunshine_duration[0] / 3600))
console.log('time:', localTime(time[0]))
console.log('sunrise:', localTime(sunrise[0]))
console.log('sunset', localTime(sunset[0]))
console.log('utc offset in seconds:', data.utc_offset_seconds)
}
example1().then(example2).then(example3).catch(console.error)