3

I have a typescript definition file with an interface like

   interface IStreamHandler<E> {
      stopStream(): void;
      process(E : E);
      onReady(bReady : boolean):void;
   }

I want to instantiate this so I declare a variable like

 declare var StreamHandler: IStreamHandler<E>; 

but this is not allowed.

How do I create the definition syntax so i could do this ?

   var sh = new StreamHandler<Animal>(); 
   sh.process(E: Animal){//code impl}
1
  • Can you explain more about the usecase? "declare" is usually used to tell typescript about variables that already exist but you're also saying that you want to instantiate the interface. Interfaces are never instantiated. Lots of questions. Please add more explanation. Commented Apr 28, 2015 at 10:06

2 Answers 2

4

The problem is that with an interface you need an implementation both for the static and instance interfaces, plus the constructor(new()). This would work:

interface IStreamHandler_Static {
    new<E>():IStreamHandler<E>; 
}
interface IStreamHandler<E> {
    stopStream(): void;
    process(e : E);
    onReady(bReady : boolean):void;
}

declare var StreamHandler: IStreamHandler_Static;

But if it's external, it's probably better to fully declare the class.

interface IStreamHandler<E> {
    stopStream(): void;
    process(e : E);
    onReady(bReady : boolean):void;
}

declare class StreamHandler<E> implements IStreamHandler<E> {
    constructor() {}
    stopStream(): void;
    process(e : E);
    onReady(bReady : boolean):void;
}
Sign up to request clarification or add additional context in comments.

1 Comment

I guess you would the need the class inside the module. I can't have it inside a module as the javascript library that I am writing typescript def for is not inside a module.
0

It seems to me that you want to restrict the parameter type of a function but you want to provide the implementation of the function later. This is a way to implement what I understood

interface Animals {
    walk():void
}

class Cat {
    walk =():void =>{
        alert("I am walking");
    }
}

interface IStreamHandler<E extends Animals> {
    stopStream(): void;
    process(E : E);
    onReady(bReady : boolean):void;
}

var animal:Animals = new Cat();  
var sh = <IStreamHandler<Cat>>{};

sh.process=(animal)=>{
    animal.walk();
}
sh.process(animal);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.