【问题标题】:Assign type to JSON type that might not need to be parsed将类型分配给可能不需要解析的 JSON 类型
【发布时间】:2019-02-17 19:49:03
【问题描述】:

我有这段代码。常见的问题,我不记得 API 是返回 JSON 还是解析的对象。

  github.repos.getForOrg({org}, (err: any, res: any) => {

      if (err) {
        return cb(err, null);
      }

      try {
        res = <Array<{ clone_url: string }>>JSON.parse(res);
      }
      catch (err) {
        // ignore
      }


      const cloneUrls = res.map(item => item.clone_url);

  });

然而,问题在于它识别出它是一个数组,但它不会提交数组中元素的类型。可能是一个 TS 错误,不确定,虽然它会接受它是一个数组,但不承认知道元素的类型,但这似乎很奇怪?

【问题讨论】:

    标签: typescript tsc typescript3.0


    【解决方案1】:

    由于resany 类型,TypeScript 将允许使用任何参数调用任何方法名称(包括map)。通过使用any 类型注释res,您已表明您希望res 具有此行为。由于回调将一个新变量 item 带入正文的范围,TypeScript 为您提供了一个 noImplicitAny 错误,让您有一个新的机会来决定是否也希望在 item 上的操作具有相同的松散行为。

    【讨论】:

      【解决方案2】:

      我会这样写:

      let result: Array<{ clone_url: string }> = null;
      if (res.constructor === Array) {
          result = res as Array<{ clone_url: string }>;
      } else if (typeof res === 'string') {
          result = JSON.parse(res) as Array<{ clone_url: string}>;
      } else {
          throw Error('unexpected type for github repo list response, neither array nor string');
      }
      

      之后使用result 而不是res

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-04-23
        • 2020-04-02
        • 2019-06-02
        • 2021-07-02
        • 1970-01-01
        • 1970-01-01
        • 2018-01-04
        相关资源
        最近更新 更多