我知道已经有很多关于这方面的话题了,但是我已经尝试了150个东西,但是没有什么效果,问题肯定来自我的逻辑,但是在哪里呢?
我的自定义表达式类型文件基本上如下所示,我添加了两个在express请求中不存在的值,到目前为止没有问题,它可以:
./src/@types/express/index.d.ts
import * as express from 'express';
declare global {
namespace Express {
interface Request {
address?: Record<string,unknown>,
file?: Express.Multer.File
}
}
}
问题在这里,,我需要使用signedCookies
,这是一个默认情况下已经存在于请求中的属性,但是默认情况下它被设置为any
(这在逻辑上返回一个错误,因为我不想要any
类型)。
./src/controllers/usersController.ts
'use strict';
import { Request, Response } from 'express';
export function getLogin(req: Request, res: Response) {
const signedCookies = req.signedCookies;
}
req.signedCookies
上的错误:
value.eslint@typescript-eslint/no-unsafe-assignment
(property) Request>.signedCookies:
any
any
的任何不安全分配
因此,我测试了几十个东西,用any
以外的东西替换了any
类型,但是没有起作用,包括这个。
./src/@types/express/index.d.ts
declare namespace Express {
interface Request {
address?: Record<string,unknown>,
file?: Express.Multer.File,
signedCookies?: Record<string,unknown>
}
}
我还尝试用值重新定义express-serve-static-core
模块,或者扩展请求接口,但是没有什么工作,错误总是一样的。
我应该补充一下,对于address
、、和 file
,是有效的(可能是因为它们是不存在的值?)
./tsconfig.json
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"rootDir": "./src",
"moduleResolution": "node",
"baseUrl": "./",
"typeRoots": ["src/@types", "./node_modules/@types"],
"allowJs": false,
"sourceMap": true,
"outDir": "./dist",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"noImplicitAny": true,
"noImplicitThis": true,
"alwaysStrict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"skipLibCheck": true,
},
"include": ["src/**/*"],
"exclude": ["node_modules", "**/*.spec.ts", "test"],
}
如果有人有一个解决方案,一个主题或任何可以帮助我的东西,我很感兴趣!
谢谢!
发布于 2022-06-26 05:40:37
这是TS的一个限制,据我所知,这是因为您不能覆盖接口的键。IIRC这是一个有意做出的设计决定,在可预见的将来可能无法改变。
例如:
// imagine this definition is from the library
namespace Express {
export interface Request {
signedCookies?: any
}
}
namespace Express {
export interface Request {
signedCookies?: Record<string, unknown>
// ^ Subsequent property declarations must have the same type.
// Property 'signedCookies' must be of type 'any',
// but here has type 'Record<string, unknown> | undefined'.
}
}
相反,您可以完全覆盖模块类型,这反过来允许您覆盖接口。
在globals.d.ts
(或任何.d.ts文件)中
import * as Express from "express";
declare module "Express" {
interface Request {
signedCookies?: unknown
}
}
然后这就起作用了:
export function getLogin(req: Request, res: Response) {
const signedCookies = req.signedCookies;
// ^? type = unknown
}
阅读有关模块重写的更多信息,请参见以下问题:How to override or extend a libary type definition in Typescript
https://stackoverflow.com/questions/72744595
复制相似问题