Skip to content

Instantly share code, notes, and snippets.

@Hachikoi-the-creator
Created July 19, 2023 01:36
Show Gist options
  • Save Hachikoi-the-creator/ea392508852ead06caf9bec5401ccd0e to your computer and use it in GitHub Desktop.
Save Hachikoi-the-creator/ea392508852ead06caf9bec5401ccd0e to your computer and use it in GitHub Desktop.
avoid bad practice in data fetch+ TS
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