在第 3 方库中重新声明不正确的打字稿类型 [英] redeclare incorrect typsescript type in 3rd party library
问题描述
我正在使用带有 @types/winston 类型的 winston 3.0.这些类型尚不完全兼容,我在类型中遇到了错误,我不知道如何更正.
这是我的代码.
logger.ts
导出函数 middleware(): express.Handler {const 运输 = 新 winston.transsports.Console({json:是的,着色:真实,字符串化:getStringify()});const loggerOptions: expressWinston.LoggerOptionsWithTransports = {运输:[运输],元:真实,msg: "HTTP {{req.method}} {{req.url}}",快递格式:真,着色:假};返回 expressWinston.logger(loggerOptions);}
loggerOptions 上的 ts 错误是
<块引用>'TransportInstance' 类型中缺少属性 'writable'
如果我使用 NodeJS.WriteStream 扩展 @types/winston 中的 TransportInstance 接口,问题就解决了.即改变这个:
interface TransportInstance 扩展了 TransportStatic,NodeJS.EventEmitter {
为此:
interface TransportInstance extends TransportStatic, NodeJS.EventEmitter, NodeJS.WriteStream {
但当然,我无法更改它,因为它是第 3 方依赖项,并且声明在 node_modules 中.那么如何重新声明作为 npm 依赖项导入的接口?
我已经开始研究声明合并::>
logger.d.ts
import * as winston from "winston";导出命名空间温斯顿{导出接口 TransportInstance扩展 winston.TransportInstance,NodeJS.WriteStream {}}
但这没有任何影响.我不确定如何将此接口导入 logger.js 而不是导入 winston 库时出现的接口.
谢谢
尝试使用 模块扩充.这对我有用:
声明模块winston"{接口 TransportInstance 扩展了 NodeJS.WriteStream {}}
I'm using winston 3.0 with the @types/winston types. These types are not yet fully compatible, and I've come across an error in the types which I don't know how to correct.
Here's my code.
logger.ts
export function middleware(): express.Handler {
const transport = new winston.transports.Console({
json: true,
colorize: true,
stringify: getStringify()
});
const loggerOptions: expressWinston.LoggerOptionsWithTransports = {
transports: [transport],
meta: true,
msg: "HTTP {{req.method}} {{req.url}}",
expressFormat: true,
colorize: false
};
return expressWinston.logger(loggerOptions);
}
The ts error on loggerOptions is
Property 'writable' is missing in type 'TransportInstance'
The problem is fixed if I extend the TransportInstance interface in @types/winston with NodeJS.WriteStream. i.e. change this:
interface TransportInstance extends TransportStatic, NodeJS.EventEmitter {
to this:
interface TransportInstance extends TransportStatic, NodeJS.EventEmitter, NodeJS.WriteStream {
But of course, I can't change that because it's a 3rd party dependancy and the declaration is in node_modules. So how do I redeclare an interface which I've imported as an npm dependency?
I've started looking into Declaration Merging:
logger.d.ts
import * as winston from "winston";
export namespace winston {
export interface TransportInstance
extends winston.TransportInstance,
NodeJS.WriteStream {}
}
But this doesn't have any impact. I'm not sure how to import this interface into logger.js instead of the one that comes in when I import the winston library.
Thanks
Try using module augmentation. This works for me:
declare module "winston" {
interface TransportInstance extends NodeJS.WriteStream {}
}
这篇关于在第 3 方库中重新声明不正确的打字稿类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!