【问题标题】:Node.js Typescript how to assign Request.payload to self-defined interfaceNode.js Typescript如何将Request.payload分配给自定义接口
【发布时间】: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 SampleRequest.payload 的类型是 string | object | Buffer | internal.Readable。我尝试使用类型保护 const input: SampleInput = (&lt;object&gt;request.payload);,但仍然得到类似 {} is not assignable to Sample 的东西。

如何定义类型并直接为其分配有效负载?

【问题讨论】:

    标签: javascript node.js typescript hapijs


    【解决方案1】:

    &lt;object&gt; 类型断言不起作用,因为SampleInput 不仅仅是一些随机对象,object 基本上指定了一个一般的对象,即没有特定键的非原始类型(参见@987654321 @)。 SampleInputobject 的超集。 SampleInput 可以分配给 object 变量,反之则不行。

    考虑到已知payloadSampleInput,因为它是在运行时验证的,它应该是:

    const input = <SampleInput>request.payload;
    

    预计会起作用,因为request.payload字符串 | 对象 |缓冲区 | internal.Readable,因此可以将其声明为 SampleInput(否则可能需要像 &lt;SampleInput&gt;&lt;any&gt;request.payload 这样的 hack)。

    【讨论】:

    • 嗨,这个语法是否等同于request.payload as SampleInput
    • @ErnestJones 是的,as 是较新的语法,通常更推荐使用,因为它不需要调整即可与 JSX 兼容。
    猜你喜欢
    • 2017-07-21
    • 1970-01-01
    • 2020-08-18
    • 2017-07-03
    • 2015-10-11
    • 1970-01-01
    • 2018-08-15
    • 2018-12-07
    • 1970-01-01
    相关资源
    最近更新 更多