首页 > 解决方案 > 如何修复反应和打字稿中的类型错误?

问题描述

我的代码如下所示,

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 {};
  }

},

不确定是什么问题。有人可以帮我解决这个问题。谢谢。

标签: javascriptreactjstypescript

解决方案


推荐阅读