Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a function in an interface React Typescript

I have a setup like this:

enum PokemonType {
    Dark = "DARK"
    Light = "Light"
}

const pokemonTypes: {[key: string]: PokemonInfo} = {
    "DARK": {
        info: "Dark is bad",
        color: "black"
    },
    "Light": {
        info: "Light is good",
        color: "white"
    }
}

interface Pokemon {
    type: PokemonType,

    // !!Some kind of function here to use type
    // to index into pokemonTypes.!!
}

See the comment above in Pokemon. Basically I want a function in the Pokemon interface to use the type key to index into the pokemonTypes const. How could I do this? Thanks!


1 Answers

Easy: Just define them as arrow functions like this:

interface Pokemon {
  type: PokemonType;
  attack: () => void;
  eat: (food: Food) => {liked: boolean, health: number};
  isType: (type: PokemonType) => boolean;
}

if you want to have different types based on what kind of type it is, you'll have to declare it like this

interface WaterPokemon {
 type: PokemonType.WATER;
 squirt: () => void;
}

interface FirePokemon {
 type: PokemonType.LIGHT;
 spewFire: () => void;
}

//...and so on

type Pokemon = WaterPokemon | FirePokemon;

Remember that in typescript all your types have to be static and immutable in order for typing and autocorrection to work, since the typescript compiler does not actually execute any code, but rather checks that the types of your variables etc are consistent. It uses static code analysis to do so but your pokemonTypes object is mutable at runtime.

like image 159
IcyTv Avatar answered Oct 30 '25 08:10

IcyTv