call signature implementation

Topics: Language Specification
Oct 30, 2012 at 1:54 PM
Edited Oct 30, 2012 at 1:57 PM

In the video I've seen strange code example and I'd like to know how to use the interface below, I mean how to implement the class or make the constructor to initialize the member f.

 

interface X{
    f:{ 
        (s:string):string;
        (s:number):string;
        data:any;
    };
}
class xxx
{
// how to initialize this structure ?
    f:{   
        (s:string):string;
        (s:number):string;
        data:any;
    };
}

var x = new xxx();
function a(x:X):string{
    return x.f("1");    
}
a(x);
 
Oct 30, 2012 at 3:20 PM

The only solution I've found is to use type cast. It works, but looks quite ugly. To me this is an error in the compiler or there should be different way to do this.

interface X{
    f:{ 
        (s:string):string; 
        (s:number):string; 
        data:any; 
    };
}

class xxx
{
    constructor()
    {
        this.f = <{ (s:string):string; (s:number):string; data:any; }> function (s:any):string {return s.toString();};
        this.f.data = "data" 
    };

    f:{ 
        (s:string):string;
        (s:number):string;
        data:any;
    };
}


var x = new xxx();

function a(x:X):string{
    return  x.f("1") + x.f(1) + x.f.data;     
}

alert(a(x));

Coordinator
Oct 30, 2012 at 9:34 PM

Indeed, that's one way to do it, and it's not terribly attractive.  Interfaces as a whole cover a lot of ground, as it's how we describe typing most of JavaScript.  There are some kinds of typing that you can describe with interfaces that are difficult to create easily in TypeScript, like the one you show.  This falls into an expand-style, where you start with one object and extend it with a few more features.  In this case, we just use the <> operator like you have.  With luck some of these implementations will become easier in the future.