以下源代码返回 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;
}
});
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/