javascript - 如何修复反应和打字稿中的类型错误?
问题描述
我的代码如下所示,
itemDetails: async (parent, args, { dataSources: { someAPI } }) => {
const source = get(parent, 'source');
const id = get(parent, 'id');
if (id) {
let output;
if (source === 'source1') {
const data = await someAPI.getItem(id);
output = {
id: data.id,
name: data.name,
}
}
if (source === 'source2') {
const data = await someAPI.getItem(id);
output = {
id: data.id,
name: data.name,
}
}
if (output) {
return {
id: output.id,
name: output.name,
}
} else {
return {};
}
} else {
return {};
}
},
上面的代码有效,但是如果我在每个 if 条件中返回输出,如下面的代码,它会抛出错误
类型 ID?: any, name?: any 不能分配给 id?undefined , name?: 未定义类型
itemDetails: async (parent, args, { dataSources: { someAPI } }) => {
const source = get(parent, 'source');
const id = get(parent, 'id');
if (id) {
if (source === 'source1') {
const data = await someAPI.getItem(id);
return { //returning here
id: data.id,
name: data.name,
}
}
if (source === 'source2') {
const data = await someAPI.getItem(id);
return { //returning here
id: data.id,
name: data.name,
}
}
} else { //no id
return {};
}
},
不确定是什么问题。有人可以帮我解决这个问题。谢谢。
解决方案
推荐阅读
- nginx - GKE Nginx 入口控制器 Oauth2 代理重定向
- angular - 角度数据表不显示表中的数据
- javascript - HTML 之后的 JS 与内部的 onload 方法
- android - RecyclerView findViewHolderForAdapterPosition() 返回 null 即使关联的行没有被回收
- aws-lambda - 安装无服务器框架以在 aws lambda 中执行 nodejs 应用程序
- html - Bootstrap flexbox 列彼此相邻而不是彼此下方
- sql - 宏中的 SAS Proc SQL
- android - 如何创建带有渐变的圆角矩形角进度条?
- excel - 从具有动态范围的选定文件中浏览和复制数据
- pip - 无法在 Conda 环境中使用 pip 安装软件包