簡體   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