Skip to content

Instantly share code, notes, and snippets.

@santospatrick
Last active July 30, 2022 16:00
Show Gist options
  • Save santospatrick/a0967dda9b804b482349454ae08b5518 to your computer and use it in GitHub Desktop.
Save santospatrick/a0967dda9b804b482349454ae08b5518 to your computer and use it in GitHub Desktop.
Typescript exercises based in real world examples
// ===================
// Typescript Exercises
// ===================
// Utility types: https://www.typescriptlang.org/docs/handbook/utility-types.html
// Reference: https://pokeapi.co/api/v2/pokemon?limit=10
type Pokemon = unknown
const bulbasaur: unknown = {
name: 'bulbasaur',
url: 'https://pokeapi.co/api/v2/pokemon/1/',
base_experience: 64,
}
// 1. Type "bulbasaur" variable so you don't see any errors
console.log(bulbasaur.name)
// 2. "pikachu" does not have "url" property, make it optional
const pikachu: unknown = {
name: 'pikachu',
base_experience: 64,
}
// 3. "venusaur" has a lot of abilities! type an array for its abilities
const venusaur: unknown = {
name: 'pikachu',
base_experience: 64,
abilities: ["overgrow", "chlorophyll"]
}
// 4. Type the component below and pick only "name"
// property from "Pokemon" and merge with component props
type FirstExerciseProps = {
url: string
} & unknown
const ShowPokemonName = ({ url, name }: FirstExerciseProps) => {
return <a href={url}>{name.toLowerCase()}</a>
}
// 5. Type the component below and omit only "url"
// property from "Pokemon", which is not going to be used
type SecondExerciseProps = unknown
const ShowAllPokemonAttrsButURL = ({ name, base_experience, abilities }: SecondExerciseProps) => {
return <p>{name} has base experience of {base_experience}, and the following abilities: {abilities?.join(', ')}</p>
}
// 6. Type the component below so we pick only "name" and "abilities"
// from "Pokemon" type and make them required
type ThirdExerciseProps = unknown
const ShowAllPokemonAbilities = ({ name, abilities }: ThirdExerciseProps) => {
return <p>{name} following abilities: {abilities.join(', ')}</p>
}
// 7. Type the function below so it receives "Pokemon" and any
// other attribute to be updated
function updatePokemonObject(pokemon: Pokemon, newValues: unknown) {
return {
...pokemon,
...newValues
}
}
updatePokemonObject(bulbasaur, { name: "Ivysaur", abilities: ["sludge_bomb", "solar_beam"] })
// 8. BONUS EXERCISE (Optional)
// figure it out!!!
type PokemonNames = unknown
const pokemons: unknown = {
bulbasaur: { name: "bulbasaur", url: "https://bulbasaur.com", base_experience: 100 },
pikachu: { name: "pikachu", base_experience: 120 },
venusaur: { name: "venusaur", base_experience: 140 }
}
console.log(pokemons.bulbasaur.url)
console.log(pokemons.pikachu.abilities)
console.log(pokemons.venusaur.name)
// "Agumon" is not a pokémon!!
// this should be the only error you see in this file
console.log(pokemons.agumon.name);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment