redeclare incorrect typsescript type in 3rd party library

喜欢而已 提交于 2021-02-10 05:20:22

问题


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


回答1:


Try using module augmentation. This works for me:

declare module "winston" {
    interface TransportInstance extends NodeJS.WriteStream {}
}


来源:https://stackoverflow.com/questions/51734248/redeclare-incorrect-typsescript-type-in-3rd-party-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!