【问题标题】:How to add a function in an interface React Typescript如何在接口 React Typescript 中添加函数
【发布时间】:2020-12-28 09:40:38
【问题描述】:

我有这样的设置:

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 接口中的一个函数使用type 键来索引pokemonTypes const。我怎么能这样做?谢谢!

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

    简单:只需将它们定义为像这样的箭头函数:

    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 中,所有类型都必须是静态且不可变的,以便键入和自动更正工作,因为 typescript 编译器实际上并不执行任何代码,而是检查变量等的类型是否一致。它使用静态代码分析来执行此操作,但您的 pokemonTypes 对象在运行时是可变的。

    【讨论】:

      猜你喜欢
      • 2021-06-29
      • 2021-11-10
      • 1970-01-01
      • 2021-12-17
      • 2020-01-07
      • 1970-01-01
      • 2020-08-01
      • 2018-08-28
      • 2021-10-26
      相关资源
      最近更新 更多