typescript, node, express: adding ts properties to Request

typescript, node, express: adding ts properties to Request

If you use typescript with node+express and you add some context to the Request parameters, you need to adjust your Request type to reflect the additional properties. Otherwise, your IDE may flag any accesses to these properties as errors.

Let’s assume you will add an “environment” property to Request. You’ll want to have that property available to typescript.

I always have a types folder sitting around in my “src” directory that has a types.d.ts file. You do not need to put this into a type roots folder and change tsconfig.json. Here’s my adjusment:

import { Request, Response, Send } from  "express"
import  *  as  env  from  "../interfaces/Environment"

// add our addition to Request
declare  global {
	namespace  Express {
		interface  Request {
			environment:  env.Environment
		}
		interface  Response {
		    // holds original Response.sense, used for overrides.
			sendResponse:  Send
		}
	}
}

Comments

Popular posts from this blog

zio layers and framework integration

typescript and react types

dotty+scala.js+async: interesting options