代码之家  ›  专栏  ›  技术社区  ›  sunknudsen

如何修复类型“Boom<any>|ResponseObject”上不存在类型脚本错误属性“isBoom”

  •  0
  • sunknudsen  · 技术社区  · 6 年前

    this.hapi.ext({
      type: 'onPreResponse',
      method: async (request, handler) => {
        if (request.response.isBoom && request.response.message !== 'Invalid request payload input') {
          if (request.response.isServer) {
            logger.captureException(request.response, null, {
              digest: this.requestDigest(request)
            });
          } else {
            logger.captureMessage(request.response.message, 'info', null, {
              digest: this.requestDigest(request)
            });
          }
        }
        return handler.continue;
      }
    });
    

    enter image description here

    类型“Boom | ResponseObject”上不存在属性“isBoom”。 类型“ResponseObject”上不存在属性“isBoom”。

    类型“Boom”上不存在属性“isServer”| 响应对象'。类型上不存在属性“isServer”

    不可分配给“string”类型的参数。键入“(httpMessage:

    @types/hapi ?

    1 回复  |  直到 6 年前
        1
  •  2
  •   Titian Cernicova-Dragomir    6 年前

    自从 response 这是一个联盟 ResponseObject | Boom | null 除非我们使用类型保护,否则我们只能访问联盟的普通成员。

    有几种类型的类型保护,您可以阅读更多关于 here .下面我使用 in 根据属性的存在进行区分的类型

    import { Server } from 'hapi';
    
    const hapi = new Server({})
    
    hapi.ext({
        type: 'onPreResponse',
        method: async (request, handler) => {
            if (request.response && 'isBoom' in request.response && request.response.message !== 'Invalid request payload input') {
                if (request.response.isServer) {
                    request.response.message // string 
                }
                return handler.continue;
            }
        }
    });
    

    因为类型 Boom a班是a班吗 instanceof typeguard还应适用于:

    hapi.ext({
        type: 'onPreResponse',
        method: async (request, handler) => {
            if (request.response && request.response instanceof Boom && request.response.message !== 'Invalid request payload input') {
                if (request.response.isServer) {
                    request.response.message // string 
                }
                return handler.continue;
            }
        }
    });
    

    笔记 在这两种情况下,我都添加了一个 request.response 排除 null 来自工会。只有在以下情况下,编译器才需要此选项: strictNullChecks

    推荐文章