1

Like the title states, I would like to rewrite the statement below in TypeScript

EventEmitter = require('events').EventEmitter

to ES6 style

import {EventEmitter} from "events"

I'm not sure whether these two are equivalent, in fact I think they aren't because when I'm trying to use RxJS with the second statement above it doesn't compile the example below whereas it does with the first one.

I'm getting the following error when I'm using the second statement above.

.build/lib/process.ts(12,3): error TS2345: Argument of type 'EventEmitter' is not assignable to parameter of type '{ on: (name: string, cb: (e: any) => any) => void; off: (name: string, cb: (e: any) => any) => vo...'.
    Property 'off' is missing in type 'EventEmitter'.

Example:

var EventEmitter = require('events').EventEmitter,
    Rx = require('rx');

var eventEmitter = new EventEmitter();

var source = Rx.Observable.fromEvent(
  eventEmitter,
  'data',
  function (foo, bar) { return { foo: bar, bar: bar }; });

var subscription = source.subscribe(
  function (x) {
    console.log('Next: foo -' + x.foo + ', bar -' + x.bar);
  },
  function (err) {
    console.log('Error: ' + err);
  },
  function () {
    console.log('Completed');
  });

eventEmitter.emit('data', 'baz', 'quux');
// => Next: foo - baz, bar - quux
iam3yal
  • 2,188
  • 4
  • 35
  • 44
  • possible duplicate of [ES6 - Convert from 'require' to 'import'](http://stackoverflow.com/q/30898686/1048572) - not sure because of the Typescript involvement though – Bergi Jun 07 '16 at 03:01

3 Answers3

0

Never mind it works! it's just an issue with Rx definition files.

I changed the following.

import * as Rx from "rx"

to

const Rx = require('rx')

and kept the ES6 import style to import the EventEmitter.

iam3yal
  • 2,188
  • 4
  • 35
  • 44
0

Argument of type 'EventEmitter' is not assignable

Reading the docs : https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/fromevent.md your example should definitely work.

This is a bug in the definitions for RX. The type definitions should explicitly support EventEmitter or make it compatible with EventEmitter instances.

basarat
  • 261,912
  • 58
  • 460
  • 511
0

I don't like the solution but what I did to make it work is switch off the types using 'any'.

var eventEmitter: any = new EventEmitter();
iam3yal
  • 2,188
  • 4
  • 35
  • 44