Overwrite `any` in TypeScript when merging interfaces

前端 未结 2 1689
耶瑟儿~
耶瑟儿~ 2021-02-15 15:49

I\'m using Express and I\'m trying to explicitly define res.locals. In the @types/express package, Express.Response.locals is any, so I can\'t seem to

2条回答
  •  心在旅途
    2021-02-15 16:38

    Unfortunately there is no way to override any using interface merging. You can so some surgery on the type and replace the type using mapped and conditional types:

    import * as express from 'express'
    
    type Omit = Pick>
    
    type MyResponse = Omit & { 
      locals: {
        myVar: number
      }
    }
    function middleware(
      req: express.Request, 
      res: MyResponse, 
      next: express.NextFunction
    ) {
      res.locals.myVar = '10' // error now
      next()
    }
    

提交回复
热议问题