如何在 Typescript 中将 Express 路由的主体参数获取为 'string' 而不是 'any'?

How to get Express route's body parameters as 'string' instead of 'any' in Typescript?

我正在通过 <form>:

使用隐藏的输入类型发送 string productId
<form action="/cart" method="POST">
    <button class="btn" type="submit">Add to Cart</button>
    <input type="hidden" name="productId" value="<%= product.id %> ">   // EJS template engine
</form>

然后按如下方式在 Express 路由中接收 productId

export const postCart = async (request: Request, response: Response): Promise<void> => {
    const productId = request.body.productId   // This is inferred as type 'any'
    const allProducts = //...Array<Product>
    const requestedProduct = allProducts.find((product) => product.id === productId)  // Problem: this is always false
}

问题

条件 product.id === productId 总是 false 因为来自数据库的 product.id 的类型是 stringproductId 的类型是从 bodyany。我需要一种方法让它们都属于同一类型。

到目前为止我尝试了什么

我尝试注释和转换 productId 的类型:

const productId: string = request.body.productId              // Doesn't work
const productId: string = request.body.productId as string    // Doesn't work
const productId: string = request.body.productId + ''         // Doesn't work

唯一可行的是,如果我从 ids 创建 Numbers:

Number(product.id) === Number(productId)

但这不是解决方案,因为我使用 UUID 字符串表示产品 id。并且将 UUID 转换为数字可能不是一个好主意。

如有任何意见,我们将不胜感激。

所以我们在评论部分聊了聊,但问题似乎是 html 中的尾随 space:

<input type="hidden" name="productId" value="<%= product.id %> ">

更新为:

<input type="hidden" name="productId" value="<%= product.id %>">