Last active
February 11, 2024 09:44
-
-
Save bruchmann/0a2099d02ae929a553b1208ad67ae36c to your computer and use it in GitHub Desktop.
Generics Explainer (an experiment)
This file contains hidden or 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
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") |
This file contains hidden or 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
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