Skip to content

Instantly share code, notes, and snippets.

@bruchmann
Last active February 11, 2024 09:44
Show Gist options
  • Save bruchmann/0a2099d02ae929a553b1208ad67ae36c to your computer and use it in GitHub Desktop.
Save bruchmann/0a2099d02ae929a553b1208ad67ae36c to your computer and use it in GitHub Desktop.
Generics Explainer (an experiment)
function createResponseMapper(responseType: string) {
return (response) => {
switch (responseType) {
case "Game":
return ;
case "Post":
return ;
default:
throw new TypeError(`Cannot map response of type ${responseType});
}
};
}
async function fetchAndMapData(url: string, responseType: string) {
const data = await fetch(url).then((res) => res.json());
return data.map(createResponseMapper(responseType));
}
fetchAndMapData(myPostApiUrl, "Post")
fetchAndMapData(myGameApiUrl, "Game")
function myFunction<T>(myArgument: T): T {
if (typeof myArgument === "number") {
return 42;
}
if (typeof myArgument === "string") {
return "foo";
}
throw new TypeError(`I don't know how to handle "${typeof(myArgument)}"`);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment