Typescript 重构一系列if语句
我最近开始在我的工作中扮演更多的编码角色,并承担着重构一些粗略代码的任务Typescript 重构一系列if语句,typescript,Typescript,我最近开始在我的工作中扮演更多的编码角色,并承担着重构一些粗略代码的任务 if (item.market === true) properties.marketPlace = true if (!itemHasEssentialFields(item)) properties.lackingData = true if (!item.availableOnline) properties.pickupOnly = true if (item.bundle) properties.bundle =
if (item.market === true) properties.marketPlace = true
if (!itemHasEssentialFields(item)) properties.lackingData = true
if (!item.availableOnline) properties.pickupOnly = true
if (item.bundle) properties.bundle = true
if (item.freight) properties.freightOnly = true
接下来的15行if语句将属性的不同键设置为true。重构此对象的最佳方法是什么?如果值可以是布尔值,则可以使用
对象更简洁地进行重构。分配:
Object.assign(properties, {
marketPlace: item.market,
lackingData: !itemHasEssentialFields(item),
pickupOnly: !item.availableOnline,
bundle: item.bundle, // may need to cast this to Boolean
freightOnly: item.freight, // may need to cast this to Boolean
// etc
如果properties
开始时为空,则仅使用初始值设定项直接声明对象会更好:
const properties = {
marketPlace: item.market,
lackingData: !itemHasEssentialFields(item),
pickupOnly: !item.availableOnline,
bundle: item.bundle,
freightOnly: item.freight,
// ...
如果值必须是true
或不存在,则可以通过过滤entires将上述对象转换为仅具有truthy属性的对象:
const propertiesWithHoles = Object.fromEntries(
Object.entries(properties)
.filter(entry => entry[1])
);
但这是一种奇怪的数据结构。如果可能的话,使用布尔值会更有意义。如果一条语句没有实现,属性值是否可以false
?例如,如果market
不是真的,那么properties.marketPlace
可能是false
吗?不,依赖它的代码希望不会填充对象字段,我也可以重构该代码(可能应该)我喜欢你的解决方案,但我也在考虑创建一些类型,并根据一组规则和映射动态设置这些东西,你认为如何?这是一个选项,但我不认为任何方法都会像纯对象文本那样干净和简单。