【发布时间】:2018-07-11 06:33:35
【问题描述】:
我在 hapi.js 框架中有一个 node.js API。我想为用户输入有效负载创建接口。例如:
路线定义:
{
path: "/sample",
method: "POST",
handler: myHandler,
options: {
validate: {
payload: {
number1: joi.number().required(),
string1: joi.string().required(),
number2: joi.number(),
}
}
}
}
处理程序:
interface SampleInput {
number1: number;
string1: string;
number2?: number;
}
const myHandler = async (request, h): Promise<string> => {
const input: SampleInput = request.payload;
// any works but really want to get rid of this
const _input: any = request.payload;
const input: SampleInput = _input;
// Service body
return "Hello World";
}
此代码总是显示一些错误,例如Request.payload is not assignable to Sample。 Request.payload 的类型是 string | object | Buffer | internal.Readable。我尝试使用类型保护 const input: SampleInput = (<object>request.payload);,但仍然得到类似 {} is not assignable to Sample 的东西。
如何定义类型并直接为其分配有效负载?
【问题讨论】:
标签: javascript node.js typescript hapijs