如何将fetch得到的结果`res:Proj`转为`DataType`类型?
我们在使用Form的时候,一般Form的dataSource有自己的DataType:例如定义的:
interface DataType {
key: React.Key;
id: number;
name: string;
desc: string;
loc: string;
selected: boolean;
createTime: Date;
updateTime: Date;
}
但是我fetch请求的数据有自己的类型。比如:
export interface Proj {
key: string;
id: number;
name: string;
desc: string;
loc: string; // 存放位置
createTime?: Date,
updateTime?: Date
}
请求数据:
fetch.invoke('getProj').then((res:Proj) => {
console.log('getProj:' ,res)
}
这里遇到2个问题:1)如何将得到的结果res:Proj
转为DataType
类型?2)对比DataType
和Proj
,DataType
多出key
字段,如何按照顺序进行增加到res
呢?
回复
1个回答

test
2024-06-18
新增一个转换函数,对于key字段,如果Proj类型中没有这个字段,可以在转换函数中生成这个字段:
function convertProjToDataType(proj: Proj): DataType {
return {
key: proj.key || proj.id.toString(), // 使用 Proj 的 key,如果不存在则使用 id 转换为字符串
id: proj.id,
name: proj.name,
desc: proj.desc,
loc: proj.loc,
selected: false, // 默认值,或者根据业务逻辑调整
createTime: proj.createTime || new Date(), // 如果没有提供,使用当前时间
updateTime: proj.updateTime || new Date() // 如果没有提供,使用当前时间
};
}
示例示例:
fetch.invoke('getProj').then((res: Proj) => {
const dataTypeObj = convertProjToDataType(res);
console.log('Converted DataType Object:', dataTypeObj);
});
回复

适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容