Home > front end >  How to use express.js req.params with typescript
How to use express.js req.params with typescript

Time:11-04

I have express.js controller and I can't use req.params

The error is Property 'id' is missing in type 'ParamsDictionary' but required in type 'IParam'.

I need to get id from param with type string

import { Request, Response } from 'express'

interface IParam {
    id: string
}

const Update = (req: Request, res: Response) => {
    const { id }: IParam = req.param // The error occured here
}

export default Update

CodePudding user response:

Your main issue is that you're trying to cast req.params.id (a string) as IParam (an object).

You can typically just use this...

const { id } = req.params;

because Express defines the default params type as

export interface ParamsDictionary {
    [key: string]: string;
}

Otherwise, you can strongly type the Request to include your params

const Update = (req: Request<IParam>, res: Response) => {
  const { id } = req.params;
}

CodePudding user response:

You should probably use a type assertion here:

interface IParam {
    id: string
}

const Update = (req: Request, res: Response) => {
    const { id } = req.param as unknown as IParam
}

export default Update

An assertion tells TypeScript that you know what you're doing. Previously, you had a type annotation, so TypeScript was really eager to jump in and check the assignment.

  • Related