Created
July 19, 2023 01:36
-
-
Save Hachikoi-the-creator/ea392508852ead06caf9bec5401ccd0e to your computer and use it in GitHub Desktop.
avoid bad practice in data fetch+ TS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type SomeRes = { | |
id: number; | |
title: string; | |
}; | |
const fetchSomeStuff = async () => { | |
const res = await fetch("..."); | |
if (res.ok) { | |
const data: SomeRes = await res.json(); | |
// no error even tho the link doesn't even exist | |
data.title; | |
} | |
// * how it should be | |
if (res.ok) { | |
const data = await res.json(); | |
// no error even tho the link doesn't even exist | |
if (!("title" in data)) { | |
return console.error("missing prop title"); | |
} | |
// And so on .... OR | |
if (!("title" in data)) { | |
data.title = "default-value"; | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment