繁体   English   中英

如何在接口 React Typescript 中添加 function

[英]How to add a function in an interface React Typescript

我有这样的设置:

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.!!
}

请参阅Pokemon上面的评论。 基本上我想要Pokemon接口中的 function 使用type键来索引pokemonTypes const。 我怎么能这样做? 谢谢!

简单:只需将它们定义为箭头函数,如下所示:

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

如果你想根据它的类型有不同的类型,你必须像这样声明它

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

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

//...and so on

type Pokemon = WaterPokemon | FirePokemon;

请记住,在 typescript 中,所有类型都必须是 static 并且不可变,以便键入和自动更正工作,因为 typescript 编译器实际上不会执行任何代码,而是检查变量的类型等是否一致。 它使用 static 代码分析来执行此操作,但您的 pokemonTypes object 在运行时是可变的。

暂无
暂无

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

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