justin
justin

Reputation: 3607

Change type imported from typings definition

I'm just getting started with Typescript and am trying to get the compiler to let me do replServer.context.something = 123 in the following:

import repl = require('repl');

let replServer = repl.start({
  prompt: '>> '
});

replServer.context.something = 123;

but it's complaining with: "Property 'context' does not exist on type 'EventEmitter'".

I have installed the type definitions with typings install dt~node --save --global and the repl module is defined as follows in typings/globals/node/index.d.ts:

declare module "repl" {
    import * as stream from "stream";
    import * as events from "events";

// ...
    export function start(options: ReplOptions): events.EventEmitter;
}

I would imagine the solution involves defining my own type extending events.EventEmitter which has a context of type any (object?), and then somehow overriding the definition in typings/globals/node/index.d.ts to use the new type.

Is this right? How is it done? (I would imagine you leave typings/globals/node/index.d.ts alone and add another file somewhere (probably outside typings directory)).

Does the order in which Typescript read these definition files (index.d.ts and the one which overrides this definitions) matter?

Thanks!

Edit 1:

I ended up trying what I had in mind and it's working (but it depends on directory naming... i.e. a hack).

I added typings2/node/index.d.ts with the following:

declare module "repl" {
    import * as events from "events";

    interface ReplEventEmitter extends events.EventEmitter {
      context: any;
    }

    export function start(options: ReplOptions): ReplEventEmitter;
  }

It works fine (i.e. previous definitions are kept and a context is added), but it depends on the directory I put it in being named something which comes after typings.

I'm using Atom and the plugin I'm using automatically changes the "files" field in tsconfig.json to list the files to be included for compilation.

If my file comes before typings/globals/node/index.d.ts in "files" (managed by Atom plugin), this doesn't work. It needs to come after it (otherwise, this takes effect: export function start(options: ReplOptions): events.EventEmitter;).

What's the "proper" way of doing this?

Upvotes: 2

Views: 2584

Answers (1)

basarat
basarat

Reputation: 275857

What's the "proper" way of doing this?

External module definitions suffer from getting locked. If context is something is supported, suggest you make a PR to the original definition file.

Alternative

Create a local copy of the typings file and no long depend on the upstream version. I do this as well : https://github.com/alm-tools/alm/tree/master/src/typings

Still better than JavaScript (no help at all).

Upvotes: 2

Related Questions