简体   繁体   English

如何在接口 React Typescript 中添加 function

[英]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 .请参阅Pokemon上面的评论。 Basically I want a function in the Pokemon interface to use the type key to index into the pokemonTypes const.基本上我想要Pokemon接口中的 function 使用type键来索引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.请记住,在 typescript 中,所有类型都必须是 static 并且不可变,以便键入和自动更正工作,因为 typescript 编译器实际上不会执行任何代码,而是检查变量的类型等是否一致。 It uses static code analysis to do so but your pokemonTypes object is mutable at runtime.它使用 static 代码分析来执行此操作,但您的 pokemonTypes object 在运行时是可变的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM