typescript - 如何动态解释对象的属性具有特定类型的TS
问题描述
沙箱中的代码示例:https ://codesandbox.io/s/typescript-playground-pzl2s
我遇到的问题对象有两种类型的属性。在某个时间点,从仅包含子属性的数据库中获取数据,DRI
并根据父属性添加额外的子属性。
父属性和整个对象的类型定义如下:
type BalanceModelSectionType = {
DRI: {
AI: number;
AMDR: {
from: number;
to: number;
[index: string]: number;
};
EAR: number;
RDA: number;
UL: number;
unit: string;
[index: string]: string | number | object;
};
quantity: number;
converted: {
quantity: number;
unit: string;
};
percentage: number;
};
type BalanceModelContainerSectionType = {
DRI: {
AI: number;
AMDR: {
from: number;
to: number;
[index: string]: number;
};
EAR: number;
RDA: number;
UL: number;
SC: number;
[index: string]: number | object;
};
percentage: number;
accomplished: number;
};
type BalanceModelType = {
alanine: BalanceModelSectionType;
arginine: BalanceModelContainerSectionType;
// ... many others
[index: string]: BalanceModelSectionType | BalanceModelContainerSectionType;
};
在某个类型点收到以下对象,但它仍然缺少一些添加到其中的属性,forEach
但会导致属性丢失的 TS 错误
const model: BalanceModelType = {
alanine: {
DRI: {
AI: 0,
AMDR: {
from: 0,
to: 0
},
EAR: 0,
RDA: 0,
UL: 0,
unit: ``
}
},
arginine: {
DRI: {
AI: 0,
AMDR: {
from: 0,
to: 0
},
EAR: 0,
RDA: 0,
UL: 0,
SC: 0
}
}
};
const defaultSectionValues = {
quantity: 0,
converted: {
quantity: 0,
unit: ``
},
percentage: 0
};
const progressSectionValues = {
percentage: 0,
accomplished: 0
};
Object.keys(model).forEach(sectionName => {
const section = model[sectionName];
/*
How to dynamically explain TS that the property of the object has specific type? */
if (sectionName === `alanine`) {
model[sectionName] = { DRI: section.DRI, ...progressSectionValues }; // Property 'SC' is missing in type
} else {
model[sectionName] = { DRI: section.DRI, ...defaultSectionValues }; // Property 'unit' is missing in type
}
});
如果您能建议一种更正确的方法来为对象提供类型,或者可能以有条件的方式处理类型,我将不胜感激?
解决方案
type BalanceModelSectionType = {
DRI: {
AI: number;
AMDR: {
from: number;
to: number;
[index: string]: number;
};
EAR: number;
RDA: number;
UL: number;
unit: string;
[index: string]: string | number | object;
};
quantity?: number;
converted?: {
quantity: number;
unit: string;
};
percentage?: number;
};
对可空字段使用问号
推荐阅读
- c++ - 提取运算符在 istringstream 上达到 EOF,使用 int/char/string 改变行为
- r - R:dplyr 按组汇总数据,使用 nth() 调用,在聚合期间计算变量 n
- java - 服务层中 MultipartFile.transferto() 的 Mockito 测试
- python - 在 Python 中如何将字符串转换为列表
- rust - 为什么 Box<[u8]> 中的 [u8] 没有实现 AsRef<[u8]> + AsMut<[u8]>?
- r - 在 R 中的数据框中的某些列上应用自定义函数
- mysql - 如何在 MySQL 中获取所有不包含另一个字符串的字符串?
- pyspark - PySpark DateTime 函数返回空值
- javascript - 如何设置选定的选项
- ios - Firebase - .webInternalError:表示在 SFSafariViewController 或 WKWebView 中发生了内部错误