【发布时间】:2022-01-16 21:28:27
【问题描述】:
如果键的值为 null 并且键的类型是可选的,我想从对象的对象中删除键。
例如我有这样的对象接口:
Interface IObject {
amount: number;
plan: IPlan;
achieve: IAchieve;
status?: string;
rank?: number;
}
Interface IPlan {
year: string | null;
name: string;
date?: Date;
grade?: number;
}
Interface IAchieve {
pic: string;
name?: string;
date?: Date;
grade?: number;
}
并且有价值:
let data: IObject = {
amount: 2300;
plan: {
year: null;
name: 'renov';
date: null;
grade: 3;
};
achieve: {
pic: 'John';
name: null;
date: null;
grade: 3;
};
status: 'good';
rank: null;
};
我做了什么:
Object.keys(data).forEach(obj => {
if (typeof data[obj as keyof typeof IObject] === 'object') {
Object.keys(data[obj as keyof typeof any]).forEach(obj2 => {
if (data[obj as keyof typeof any][obj2] == undefined) {
delete data[obj as keyof typeof any][obj2];
}
});
}
else if (data[obj as keyof typeof any] == undefined) delete data[obj as keyof typeof any];
});
但我明白了:
“TypeError:无法将 undefined 或 null 转换为对象”
我期待结果:
data = {
amount: 2300;
plan: {
year: null;
name: 'renov';
grade: 3;
};
achieve: {
pic: 'John';
grade: 3;
};
status: 'good';
};
【问题讨论】:
-
在哪一行是错误...开始寻找那里...我猜,你的索引是错误的。
-
在我看来,您似乎试图在运行时(在执行代码期间)访问 Typescript 类型信息,这是不可能的。或者我误解了你在做什么。
-
@helle at delete data[obj as keyof typeof any][obj2];
标签: javascript node.js typescript