Reputation: 2665
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
Upvotes: 3
Views: 2096
Reputation: 83
I know this question is very old, but I would like to leave my contribution. Below is my solution:
import { ParamsDictionary as Params } from "express-serve-static-core";
export interface IRequestParams<T extends Params> extends Request {
params: T;
}
Upvotes: 0
Reputation: 164744
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;
}
Upvotes: 5
Reputation: 26326
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.
Upvotes: 1