合并接口时在TypeScript中覆盖`any` [英] Overwrite `any` in TypeScript when merging interfaces

查看:111
本文介绍了合并接口时在TypeScript中覆盖`any`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Express,并且试图显式定义res.locals.在@ types/express包中,Express.Response.locals是any,所以我似乎无法覆盖它:

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 overwrite it:

types/express/index.d.ts:

types/express/index.d.ts:

declare namespace Express {
  interface Response {
    locals: {
      myVar: number
    }
  }
}

我的中间件:

import * as express from 'express'

function middleware(
  req: express.Request, 
  res: express.Response, 
  next: express.nextFunction
) {
  res.locals.myVar = '10' // I want this to throw a compiler error
  next()
}

我希望将错误的res.locals.myVar分配给错误,但是根据我的自动完成功能,res.locals仍然是any.

I want my wrong assignment of res.locals.myVar to error, but res.locals is still any according to my autocompletion.

如何删除any并将其完全替换?

How can I remove any and completely replace it?

推荐答案

我最近遇到了这个问题,并设法通过在src文件夹中创建index.d.ts来覆盖res.locals来解决此问题,我的实现如下所示:

I recently ran into this issue and managed to resolve it by creating an index.d.ts in my src folder to overwrite res.locals, my implementation looked like this:

// src/index.d.ts

interface Locals {
  message?: string;
}

declare module 'express' {
  export interface Response  {
    locals: Locals;
  }
}

确保您也将其包含在tsconfig.json中,例如

Make sure you also have it included in your tsconfig.json, e.g

// somewhere in your tsconfig.json
  "include": [
    "src/**/*.ts"
  ]

您将像平常一样使用界面

You would use the interface just as you would normally

import { Request, Response, NextFunction } from 'express';

export const handler = (req: Request, res: Response, next: NextFunction) => {
  // should be typed
  res.locals.message = 'hello'
}

希望这会有所帮助!

这篇关于合并接口时在TypeScript中覆盖`any`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆