小编Aza*_*lou的帖子

使用打字稿过滤对象键

这是一个显示问题的沙箱。https://codesandbox.io/s/trusting-moon-n058k?file=/src/index.ts

输入

data.types = {
        starter: true,
        main: false,
        side: false,
        dessert: true,
        drink: false
    }
Run Code Online (Sandbox Code Playgroud)

期望的输出

recipe.types = ["starter", "dessert"]
Run Code Online (Sandbox Code Playgroud)

解决方案

type NewRecipeFormValues = {
    types: {
        starter: boolean,
        main: boolean,
        side: boolean,
        dessert: boolean,
        drink: boolean
    }
}

const postNewRecipe = (data: NewRecipeFormValues) => {
  let recipe = JSON.parse(JSON.stringify(data));
  recipe.types = Object.keys(data.types).filter(
    (key: keyof NewRecipeFormValues["types"]) => data.types[key]
  );
};

Run Code Online (Sandbox Code Playgroud)

问题:无论我使用什么类型,Typescript 都不会关闭。

任何帮助将不胜感激,因为我失去了理智

javascript typescript

4
推荐指数
1
解决办法
4546
查看次数

标签 统计

javascript ×1

typescript ×1