Why an API response type doesn't guarantee what the data really looks like
See why a type you write on a web API’s answer can be wrong while the check stays clean, what a broken promise looks like, a TypeError far from its cause or a believable wrong value, and check the answer as unknown with typeof, in and Array.isArray, with its own message for each missing part.
Fundamentals
TypeScript
Why an API response type doesn't guarantee what the data really looks like. Read this lesson at .
Tested with TypeScript 7.x · Node.js LTS
Last lesson your program asked Open-Meteo for tomorrow's highest
temperature. Tonight you want the lowest one instead: it decides
whether you need a coat at seven in the morning. So you change one
word of the address, temperature_2m_max to temperature_2m_min,
and run npm run check (npm, the Node package manager, runs TaskKit's
check script, tsc). Clean. Then you run the program, and it
prints No forecast: Cannot read properties of undefined (reading '1'). TypeScript checked every line and found nothing, and the
program broke anyway.
Think of ordering eggs online. Before the parcel comes, you write on
your shopping list what you ordered: "12 eggs". Everything you plan
with that list agrees with it, and nobody ever compares the list with
the parcel: only opening it tells you what is really inside. The type
you write on the answer of a web API (application programming
interface, a website that answers programs with data; the answer is
also called its response) is that list. TypeScript checks your code
against it, and never sees the parcel. By the end of this lesson your
program opens the parcel itself: it asks questions of the answer
before it uses it, and says exactly what is missing.
Your type is a promise nobody checks
Open weather.ts in ~/projects/taskkit, as it was at the end of
lesson 12.4: the two interfaces, url and the try / catch, with
forecast_days=2 and [1] as that lesson left them. Make one change
on line 13, temperature_2m_min where temperature_2m_max was. The
whole file is here, in case yours differs:
The check prints only its two > lines: no error. The run prints
this:
Outputtext
No forecast: Cannot read properties of undefined (reading '1')
Open-Meteo answered exactly what the address asked for: a daily
with time and temperature_2m_min, and no temperature_2m_max.
Your Forecast says something else, and nothing compared the two.
Remember what TypeScript does. It reads your files before they run,
and checks each line of your code against your types: in lesson 12.1
it caught back.titel because Task has no titel. But it checks
your code against your type, never your type against the answer. The
answer does not exist while TypeScript checks; it arrives only when
Node runs the program, and by then, as lesson 8.2 showed, every type
has vanished. Switch between the two runs, press Next step to
walk through one, or let it play:
const forecast: Forecast = await response.json(); passes because the
answer is any (lesson 12.4), and a type written on an any is a
promise, as lesson 12.1 called it: your word about what will come, not
a Promise object, and TypeScript trusts it without being able to
test it.
How an answer can differ from its type
Here the promise broke because you changed the question and not the
type. It breaks for other reasons too. The people who run an API can
rename a property or move it in a new version, and your program
learns it on the day it stops working. An answer can also have
every name your type expects and still hold the wrong kind of value
in one of them. Three kinds of difference come up again and again:
What arrives
Where your program notices
No property of that name
The first line that reads from it throws
Text where a number was promised
Maybe never: "13.3" + 1 is "13.31"
null for a missing value
Maybe never, as the Predict below shows
The fix is to stop trusting what you wrote and open the parcel.
unknown and questions at the edge
Lesson 8.5 gave the rule: when you cannot know what a value holds,
write unknown, and ask it questions before you use it. An API's answer is
such a value. So the box for the answer is now unknown, and a
function, tomorrowsHigh, asks about everything the program reads
before it hands back a number. Replace the whole of weather.ts
with this:
The address asks for temperature_2m_max again. The interfaces are
gone: they only described what you hoped for, and the questions now
find out what came. Line 34 puts the answer into data, typed
unknown, so nothing can be read from it unchecked. Each if in
tomorrowsHigh asks one question about one box, and throws a
message of its own when the answer is no. Each if asks the
opposite of what you want to hear, "is it not an object?", with !==
and !. So the if is true, and throws, exactly when the answer is
wrong:
Line 7, on data: is it an object, and does it have daily?
typeof says "object" for objects, lists and null alike
(lesson 7.3), so data === null rules out null. || stops at the
first question that is true (short-circuiting, lesson 3.2), so in is
reached only by an object that is not null, and may ask for a name
(lesson 7.4). After this line TypeScript knows
data has a daily, and data.daily is allowed. Its type is
unknown again: the question found the name, not what it holds.
Lines 11 to 15, on daily: the same three questions, for
temperature_2m_max.
Line 19, on highs: is it a list? typeof cannot say, since a
list is an "object" too. Array.isArray, built into
JavaScript, answers exactly that: true for a list and false for
anything else. It tells TypeScript that highs is a list, but not
of what, so it types the items any.
Line 22 keeps that any from spreading (lesson 8.5): it puts
tomorrow's item into a box typed unknown, and line 23 lets
only a number through.
All the questions sit in tomorrowsHigh, at the edge of your program,
as lesson 8.4 called readCommand: where the answer comes in, before
any line uses it. Switch between three answers: the one for max, the
one for min, and one whose number for tomorrow is null. Press
Next step to walk one through the questions, or let it play:
.json(): reachedInto data: unknown
data: passes✓An object with daily?
daily: passes✓Has the max list?
highs: passes✓Is it a list?
high: passes✓Is tomorrow a number?
console.log: reachedTomorrow: 13.3 °C
Each question stops the answers that lack what it asks for
All 10 steps shown.Step 1 of 10: .json()Step 2 of 10: dataStep 3 of 10: data: passesStep 4 of 10: dailyStep 5 of 10: daily: passesStep 6 of 10: highsStep 7 of 10: highs: passesStep 8 of 10: highStep 9 of 10: high: passesStep 10 of 10: console.log
All 10 steps shown.
.json(): reachedInto data: unknown
data: passes✓An object with daily?
daily: stops here✕Has the max list?
highs: never reachedIs it a list?
high: never reachedIs tomorrow a number?
console.log: never reachedTomorrow: 13.3 °C
daily stops hereNo forecast: no temperature_2m_max in the answer
Each question stops the answers that lack what it asks for
All 5 steps shown.Step 1 of 5: .json()Step 2 of 5: dataStep 3 of 5: data: passesStep 4 of 5: dailyStep 5 of 5: daily: stops here. No forecast: no temperature_2m_max in the answer
All 5 steps shown.
.json(): reachedInto data: unknown
data: passes✓An object with daily?
daily: passes✓Has the max list?
highs: passes✓Is it a list?
high: stops here✕Is tomorrow a number?
console.log: never reachedTomorrow: 13.3 °C
high stops hereNo forecast: no number for tomorrow
Each question stops the answers that lack what it asks for
All 9 steps shown.Step 1 of 9: .json()Step 2 of 9: dataStep 3 of 9: data: passesStep 4 of 9: dailyStep 5 of 9: daily: passesStep 6 of 9: highsStep 7 of 9: highs: passesStep 8 of 9: highStep 9 of 9: high: stops here. No forecast: no number for tomorrow
All 9 steps shown.
Run it:
Your number is tomorrow's forecast, so it will differ. Now change
line 4 to ask for temperature_2m_min once more, and run it again:
The same mistake as at the start, and this time the message names
the missing part. Put line 4 back to temperature_2m_max.
Predict before you run
On the night this lesson was written, Open-Meteo's 16-day forecast
for Kyiv ended in null: it had no number yet for the last day. The
text below is the last two days of that answer, written as JSON
(JavaScript Object Notation, values written as text). The code trusts
Forecast, as 12.4's did, and rounds the temperature with
Math.round (lesson 2.5).
Predict
What does this program print?
The common mistake: in before null
Line 7 asks three questions, and the middle one looks like it can go:
surely typeof data !== "object" has already sent everything but
objects away.
Common mistake
Using in on a value that may be null
You write line 7 with two questions instead of three:
npm run check prints its two > lines, and then this; TS18047 is
TypeScript's (TS) number for the error:
typeof null is "object", so after the first question data can
still be null, and in cannot look for a name in null. Here the
check does catch it, because it knows what typeof can say.
'data' is possibly 'null'.
The fix
Rule out null between the two:
When the check says a value is possibly null right after a
typeof … "object", the missing piece is data === null || between
the two, as on line 7.
Pass all four tasks to complete the lesson with practice. Reach the end without them and it counts as read only.
Exercises
Each one is checked in your browser. The page cannot reach a web API,
so the answers arrive as JSON text, read with JSON.parse just as
response.json() reads them: one asks what the check can see, two
ask the questions of an answer, and one follows an answer through
them.
Recap
Recap · 3 questions
Check yourself
Your type on an answer is wrong, and unchecked. What can happen?
Check yourself
Why does the answer go into a box typed unknown?
Check yourself
Why does tomorrowsHigh use Array.isArray for highs?
0 of 0 answered.
A cheat sheet to keep
Cheat sheet
Why an API response type is not a guarantee
What things are
Word
What it means
A type on an answer
Your promise; the check never tests it
The edge
Where outside data comes in: question it there
Array.isArray
Built in: true for a list, false for the rest
Code
Write
To
data: unknown
Keep the answer unread until you have asked about it
typeof data === "object"
Ask for an object; lists and null pass too
data === null
In the || chain: rule out null before in
"daily" in data
Ask for a name; data.daily is then unknown
Array.isArray(highs)
Ask for a list; its items are any
const high: unknown = …
Keep an any item from spreading
typeof high === "number"
Let only a number through
Rules
Rule
What it means
The check trusts your type
It never sees the answer, which comes later
A wrong type breaks late
A TypeError far away, or a wrong 0
Question what you read
Every name and every value your code uses
One message per question
Say what is missing, not only that it broke
Error
Module 12 on one page
Cheat sheet
Module 12: Talking to the Outside World
12.1 JSON: parse and stringify, and why JSON.parse returns
any
Code or rule
What it means
JSON.stringify(task)
Write a value out as JSON text
JSON.parse(text)
Build a value from JSON text; its type is any
const back: Task = …
Keep checking what JSON.parse gives back
A written type is a promise
The check trusts it and never reads the text
12.2 Reading and writing files
Code or rule
What it means
writeFile(file, text)
Make the file, or replace its text; await it
readFile(file, "utf8")
Read the file as a string; await it
existsSync(file)
Ask whether the file is there; no promise
ENOENT
Node's code for "no such file"
12.3 Interactive input with readline
Code or rule
What it means
createInterface({ … })
Make a reader; give it input and output
await reader.question("Name? ")
Ask, wait for Enter, get the line
reader.close()
Stop listening, so the program can end
An answer is a string
Digits too: use Number(answer) for a number
12.4 fetch: getting data from a web API
Where to go next
You can now say why a type written on an API's answer is a promise the check
cannot test, and what a broken one looks like: a TypeError far from its
cause, or a wrong value and no error at all. You can take the answer as
unknown and ask about every name and value your code reads before it uses
them, each question with a message of its own. That closes Module 12: your
programs read files, the keyboard and websites, and know not to trust any of
them blindly.
Next is Classes: properties, constructors, and methods, the first
lesson of Module 13, where TaskKit's tasks and the functions that
work on them move into one place of their own, a class.
Before you move on, delete weather.ts: it is not part of TaskKit.
Then try a wrong type on TaskKit itself: tasksFromJson
types what JSON.parse gives back as Task[]. Delete tasks.json
if it is there, add two tasks with npm start add "buy milk" "call Mom", open tasks.json, and delete the line "title": "Call Mom",
from the second task. Predict what
npm start help prints, then run it to see. Delete tasks.json to
put things right.
The address asks for temperature_2m_max, the name Forecast
says.
Every line matches Forecast. The answer does not exist yet, so
the check never sees it.
The answer arrives with temperature_2m_max: [15.1, 13.3].
forecast.daily.temperature_2m_max[1] is 13.3, as the type
said.
The check passes both; only the run meets the real answer
All 4 steps shown.Step 1 of 4: You: saveStep 2 of 4: TypeScript: checked ✓Step 3 of 4: Node: fetchStep 4 of 4: Node: Tomorrow: 13.3 °C
All 4 steps shown.
You
TypeScript
Node
You: savesavesave
TypeScript: checked ✓checked✓checked✓
Node: fetchfetchfetch
Node: TypeErrorTypeErrorTypeError
Time
The address asks for temperature_2m_min; Forecast still says
temperature_2m_max.
Every line matches Forecast. The answer does not exist yet, so
the check never sees it.
The answer arrives with temperature_2m_min: [10.7, 9.4], and
no max.
temperature_2m_max is undefined, and reading [1] of it
throws: Cannot read properties of undefined (reading '1').
The check passes both; only the run meets the real answer
All 4 steps shown.Step 1 of 4: You: saveStep 2 of 4: TypeScript: checked ✓Step 3 of 4: Node: fetchStep 4 of 4: Node: TypeError
All 4 steps shown.
TS18047
typeof lets null through: add data === null ||
Code or rule
What it means
await fetch(url)
Send a request; get a Response
response.ok
Ask whether the status is from 200 to 299
await response.json()
Read the body into a value of type any
No answer rejects
await fetch throws TypeError: fetch failed
12.5 Why an API response type doesn't guarantee what the data
really looks like
Code or rule
What it means
data: unknown
Keep the answer unread until you have asked about it
"daily" in data
Ask for a name; data.daily is then unknown
Array.isArray(highs)
Ask for a list; its items are any
The check trusts your type
It never sees the answer, which comes later
Exercise · Read the code
What the check can see
weather.ts is 12.4's version, with the two interfaces and
const forecast: Forecast = await response.json();. Which of these
does npm run check find?
Exercise · Predict the result
Which question stops it
A server that has no forecast sends daily, but with nothing in it:
null. Your final weather.ts gets this answer. What does it print?
The answerjson
{"daily":null}
Outputtext
Tomorrow: 13.3 °C
Outputtext
No forecast: no temperature_2m_max in the answer
What the check printstext
weather.ts:7:48 - error TS18047: 'data' is possibly 'null'.7 if (typeof data !== "object" || !("daily" in data)) { ~~~~Found 1 error in weather.ts:7
weather.tsts
const url = "https://api.open-meteo.com/v1/forecast" + "?latitude=50.45&longitude=30.52" + "&daily=temperature_2m_max&forecast_days=2&timezone=auto";function tomorrowsHigh(data: unknown): number { if (typeof data !== "object" || data === null || !("daily" in data)) { throw new Error("no daily in the answer"); } const daily = data.daily; if ( typeof daily !== "object" || daily === null || !("temperature_2m_max" in daily) ) { throw new Error("no temperature_2m_max in the answer"); } const highs = daily.temperature_2m_max; if (!Array.isArray(highs)) { throw new Error("temperature_2m_max is not a list"); } const high: unknown = highs[1]; if (typeof high !== "number") { throw new Error("no number for tomorrow"); } return high;}try { const response = await fetch(url); if (!response.ok) { throw new Error(`HTTP ${response.status}`); } const data: unknown = await response.json(); const high = tomorrowsHigh(data); console.log(`Tomorrow: ${high} °C`);} catch (error) { if (error instanceof Error) { console.log(`No forecast: ${error.message}`); }}
bash
node weather.ts
ts
interface Daily { time: string[]; temperature_2m_max: number[];}interface Forecast { daily: Daily;}const text = '{"daily":{"time":["2026-11-07","2026-11-08"],' + '"temperature_2m_max":[16.1,null]}}';const forecast: Forecast = JSON.parse(text);const high = forecast.daily.temperature_2m_max[1];console.log(`In two weeks: ${Math.round(high)} °C`);
weather.tsts
const url = "https://api.open-meteo.com/v1/forecast" + "?latitude=50.45&longitude=30.52" + "&daily=temperature_2m_max&forecast_days=2&timezone=auto";function tomorrowsHigh(data: unknown): number { if (typeof data !== "object" || !("daily" in data)) { throw new Error("no daily in the answer"); } const daily = data.daily; if ( typeof daily !== "object" || daily === null || !("temperature_2m_max" in daily) ) { throw new Error("no temperature_2m_max in the answer"); } const highs = daily.temperature_2m_max; if (!Array.isArray(highs)) { throw new Error("temperature_2m_max is not a list"); } const high: unknown = highs[1]; if (typeof high !== "number") { throw new Error("no number for tomorrow"); } return high;}try { const response = await fetch(url); if (!response.ok) { throw new Error(`HTTP ${response.status}`); } const data: unknown = await response.json(); const high = tomorrowsHigh(data); console.log(`Tomorrow: ${high} °C`);} catch (error) { if (error instanceof Error) { console.log(`No forecast: ${error.message}`); }}
weather.tsts
if (typeof data !== "object" || data === null || !("daily" in data)) {
Exercise · Fix the error
Ask whether it is a list
This tomorrowsHigh lost its list question, and TypeScript refuses the
line that reads highs[1]: 'highs' is of type 'unknown'. Lesson
8.5's rule holds: nothing is read from an unknown before a question.
Add the question, with the message temperature_2m_max is not a list,
so the program prints Tomorrow: 13.3 °C.
Loading the editor…
Exercise · Write the code
Ask about the current temperature
Ask Open-Meteo for current=temperature_2m instead of daily, and
the answer is shaped like text below: an object current holding
the temperature right now. Write currentTemperature so it asks
the questions of the answer the way tomorrowsHigh does and gives
back the number, and throws an error when current or its
temperature_2m is missing, or when the temperature is not a number.
(12.0 in JSON is the number 12, so it prints as 12.)