【发布时间】:2021-09-01 01:18:44
【问题描述】:
在创建要插入数据库的复杂对象时,这种情况尤其常见。我可能有一个需要 20 个字段的对象,每个字段都来自其他地方。
interface Cat {hair: HairType, name: string, ...20 other properties}
function insertCatIntoDB(cat: Cat){...}
function createCatForUser(userType: UserType){
const newCat: Partial<Cat> = {};
newCat.name = getNewCatNameForUserType(userType);
...business logic involving the setting of the other properties
insertCatIntoDB(newCat); // Problem: newCat is Partial<Cat>
// instead of Cat despite having assigned all of the properties
}
我看到了一些处理这个问题的方法。
- 将每个属性的“获取”重构为一个新函数,然后调用类似
insertCatIntoDB({hair: getHairByUserType, name: getNameByUserType, ...})
但是,如果创建属性所需的业务逻辑相对简单,您将创建 20 个函数,每个函数可能 3 行代码,它们只会被调用一次,这不利于可读性。
- 类似,但无需创建新函数,您只需在选项“内部”执行,例如
insertCatIntoDB({name: userType === UserType.girl ? 'cookie' : (userType === userType.boy ? 'tiger' : 'persian'), ...}) 但即使在这个逻辑非常简单的例子中,这很快就会变得笨拙且难以阅读。
- 做类似
insertCatIntoDB(newCat as Cat)的事情
但这没有类型检查。
我正在寻找有关处理这些情况的更好方法的建议。
【问题讨论】:
标签: javascript node.js reactjs typescript types