【发布时间】: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 都不会关闭。
任何帮助将不胜感激,因为我正在失去理智
【问题讨论】:
-
JSON.parse(JSON.stringify(data))的意义何在?它会生成data的部分深层克隆,但您不需要。 -
@axiac 不,我愿意吗? codesandbox.io/s/quizzical-cori-zrsio?file=/src/index.js我不想变异
data。 -
没关系,我确实没有。直到
-
你不会变异
data。至少不在问题中发布的代码中。你确实在let recipe = { ...data }; recipe.types.starter = true;中改变data -
是的,我在测试后注意到了这一点,但无法编辑我的评论。感谢您指出了这一点!它解决了我的一个误解。
标签: javascript typescript