【问题标题】:How can I extend Node's stream如何扩展 Node 的流
【发布时间】:2016-11-13 23:22:44
【问题描述】:

我正在尝试为 Readable Stream 创建一个方法,但在尝试了一点点之后,我就没有办法了。

import * as stream from 'stream'
//yields Property 'asdasas' does not exists on type 'Readable'
stream.Readable.prototype.asdasas 
//yields asdas does not exists on type 'typeof Readable'
stream.Readable.asdas

谁能给我一个解决方案并解释为什么会发生错误?谢谢

【问题讨论】:

    标签: node.js typescript stream


    【解决方案1】:

    解释错误发生的原因

    从 JavaScript 迁移到 TypeScript 的第一条规则:

    声明你使用什么

    https://basarat.gitbooks.io/typescript/content/docs/types/migrating.html

    这里Readable 没有您要找的会员。如果你想添加它,你需要声明它。类似的东西:

    interface Readable {
      asdfasdfasdf: any;
    }
    

    【讨论】:

    • 我正在使用 Node 的类型定义文件,在那里我可以找到 Readable 类。为什么我要声明接口,即使已经有一个同名的类?
    【解决方案2】:

    我设法扩展了它们。这种行为并不像我想象的那么不寻常(我仍然希望能解释一下“type 'Readable'”和“type 'typeof Readable'”的区别。代码:

    import * as stream from 'stream'
    
    class mod_Readable extends stream.Readable {
        pipe<T extends NodeJS.WritableStream>(destination: T, options?: { end?: boolean; }): T {
            //whatever
            return super.pipe(destination, options)
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-19
      • 2019-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多