Home > Net >  Read :id param from url as number in nodejs (Typescript)
Read :id param from url as number in nodejs (Typescript)

Time:07-10

I need to get the :id param from url as number instead of string, to pass it on typeorm to fetch the data for particular id

here's how I am doing now. with this approach I have to write one more variable and manual conversion

router.get('/users/:id', (req: Request, res: Response) => {
    const { id } = req.params;
    const idNew: number = parseInt(id);
    
    userRepo.findOne({
        where: {id: idNew}
    })
})

Here's how I want to do (if possible)

router.get('/users/:id', (req: Request, res: Response) => {
    const { id } = req.params;

    // maybe something like id as number

    userRepo.findOne({
        where: {id}
    })
})

CodePudding user response:

You can fix both the TypeScript and runtime type error without a variable by inlining the parseInt call:

router.get('/users/:id', (req: Request, res: Response) => {
    const { id } = req.params;
    
    userRepo.findOne({
        where: {id: parseInt(id)}
    })
})

CodePudding user response:

You can coerce in TS with the as keyword

router.get('/users/:id', (req: Request, res: Response) => {  
    userRepo.findOne({
        where: {id: req.params.id as unknown as number}
    })
})

But you risk a database error if req.params.id cannot be cast to an integer in the resulting query. e.g.

QueryFailedError: invalid input syntax for type integer: "foo"

  • Related