小编M. *_*Hav的帖子

使用 Typescript 自动验证请求的最佳方法是什么?

我想使用 Typescript 接口来轻松验证后端请求。有没有办法让它发生?我想做的事情的例子:

import { Request, Response } from 'express'

interface AuthenticateParams {
    email: string
    password: string
}

type AuthenticationRequest = Request & {body: AuthenticateParams}

const authenticate = async (req: AuthenticationRequest, res: Response) => {
    if (typeof req.body !== AuthenticateParams) res.status(400).send('Invalid body')

    // DO STUFF
    let stuff

    res.status(200).send(stuff)
}

export default authenticate
Run Code Online (Sandbox Code Playgroud)

node.js express typescript

7
推荐指数
1
解决办法
4327
查看次数

标签 统计

express ×1

node.js ×1

typescript ×1