node.js - 如何修复 TypeScript 错误属性 'isBoom' 在类型 'Boom<any> | ResponseObject' 上不存在

标签 node.js typescript hapi.js

以下源代码返回 TypeScript 错误:

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

Property 'isBoom' does not exist on type 'Boom | ResponseObject'. Property 'isBoom' does not exist on type 'ResponseObject'.

Property 'isServer' does not exist on type 'Boom | ResponseObject'. Property 'isServer' does not exist on type 'ResponseObject'.

Argument of type 'string | ((httpMessage: string) => ResponseObject)' is not assignable to parameter of type 'string'. Type '(httpMessage: string) => ResponseObject' is not assignable to type 'string'.

我该如何修复它们? @types/hapi 有问题吗?

最佳答案

由于 response 是一个联合 ResponseObject |繁荣| null 除非我们使用类型保护,否则我们只能访问联合体的公共(public)成员。

类型保护有多种类型,您可以阅读有关 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 是一个类,因此 instanceof 类型防护也应该起作用:

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 时,编译器才需要这样做,但无论如何这可能是一个好主意。

关于node.js - 如何修复 TypeScript 错误属性 'isBoom' 在类型 'Boom<any> | ResponseObject' 上不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54184444/

相关文章:

node.js - 使用sftp和socks5代理node.js

typescript - 使用 TypeScript 将 RxJS 运算符组合成新的运算符

javascript - typescript 表格重置()不起作用

javascript - 带有计算属性名称的 Typescript setState

javascript - Hapi js 从另一条路线访问一条路线

javascript - 多种 Joi 验证类型

javascript - next() 不会跳过中间件的其余部分

node.js - ( Node )sys 已弃用。请改用 util。 - 钛加速器

javascript - ES6 将一些函数导入为对象

node.js - Node Docker 运行,但看不到应用程序