I am converting an existing Node.js express application written in plain JS to TS. I understand why I get this error, but I do not know the correct way to fix it. The type "Request" comes from @types/express Do I have to extend this type to expect a property inside of body named product? I would to reuse the built-in types from @types/express as much as possible.
app.post('/something', function(req: Request) {
if (req.body) product = req.body.product
^^^^^^^^
})
Error from Typescript server: Property 'product' does not exist on type 'ReadableStream'. (tsserver 2339)
CodePudding user response:
You can use 'as' keyboard like this:
import { Request, Response } from 'express';
interface IProduct{
name: string;
.
.
}
app.post('/something', (req: Request) => {
if (req.body) product = (req.body as { product: IProduct }).product
});
If you want to use @types/express you can use generic types:
import { Request, Response } from 'express';
interface IProduct{
name: string;
.
.
}
app.post('/something', (req: Request<{}, {}, IProduct>) => {
if (req.body) { product } = req.body;
});
CodePudding user response:
Wherever you're passing the body
object from, make sure the object contains a product
property. If you have a typed body
, make sure to include the product
as a parameter. For example,
type ReadableStream = { product: string }
Or before you pass body
to app.post
,
body: { product: "product" }
CodePudding user response:
You do not need to type the request.
but if you can type the request, follow this order:
interface P {}; /* params */
interface ResBody {}
interface ReqBody {}
interface ReqQuery {}
app.post('/something', function(req: Request<P, ResBody, ReqBody, ReqQuery>) {
if (req.body) product = req.body.product
})
https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/express/index.d.ts#L112
and the error:
Property 'product' does not exist on type 'ReadableStream'.ts(2339)
that's because you need to import the request:
import { Request } = from 'express';
app.post('/something', function(req: Request) {
if (req.body) product = req.body.product
})
the global Request
interface is from the fetch API
.