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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With