【问题标题】:Filtering object keys with typescript使用打字稿过滤对象键
【发布时间】:2021-08-22 15:19:36
【问题描述】:

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

输入

data.types = {
        starter: true,
        main: false,
        side: false,
        dessert: true,
        drink: false
    }

期望的输出

recipe.types = ["starter", "dessert"]

解决方案

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]
  );
};

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

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

【问题讨论】:

标签: javascript typescript


【解决方案1】:

发生错误是因为编译器无法推断 key 的运行时类型,因为 Object.keys 可以返回不一定是 keyof NewRecipeFormValues["types"] 类型的任意字符串列表。

因此,你需要明确告诉编译器key确实是keyof NewRecipeFormValues["types"],这样它才能冷静下来。

为此,请使用type assertion

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) => data.types[key as keyof NewRecipeFormValues["types"]]
  );
};

检查这个playground

至于为什么不能使用key: keyof NewRecipeFormValues["types"] 语法,链接文档解释得更好。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-24
  • 2020-03-22
  • 2023-02-02
  • 2021-06-28
  • 2017-06-16
  • 1970-01-01
相关资源
最近更新 更多