How to merge generic object to a class in Typescript definition constructor?

823 views Asked by At

I have

interface MyClass {
  do(d: 1 | -1): this
}  

interface MyClassConstructor {
  new<T> (cfg?: T & MyClass): MyClass & T
}

interface Window {
  MyClass: MyClassConstructor
}

What went wrong with my definition as I couldn't make the follow work

var instance = new MyClass({
  undo: function() { this.do(-1) }
});

instance doesn't show Class members properly

enter image description here

Edit 1: I'm using Typescript 2.3.2. And the definition is to have intellisense in Javascript

Edit 2: I'm doing this to have better ideas of what the existing members are when calling new MyClass({ ... }) in my JS

1

There are 1 answers

5
Nitzan Tomer On

You cannot instantiate interfaces.
Your interfaces are not being translated into js by compiler so at runtime there's no such thing as MyClass.

You'll need to create a class like so:

class MyClassImpl implements MyClass {
    do(d: 1 | -1): this {
        return this;
    }

    undo(): this {
        return this.do(-1);
    }
}

var instance = new MyClassImpl();

(code in playground)

Or you can have it this way:

var instance = new class implements MyClass {
    do(d: 1 | -1): this {
        return this;
    }

    undo(): this {
        return this.do(-1);
    }
}();

Edit

If you already have an implementation for MyClass then this is what you need:

interface MyClass {
    do(d: 1 | -1): this
}  

interface MyClassConstructor {
    new <T>(cfg?: T): MyClass & T
}

declare const MyClass: MyClassConstructor;