tmp dev
tmp dev

Reputation: 9219

How to implement the following interface properly

I am trying to understand the concepts of interfaces and call signatures. Let say I have the following interface

interface MyInterface {
    (x: number, y: string): string;
    someProperty: (x: number, y: number) => number;
    anotherProperty: number
}

If I have the following type declaration

let myOtherInterface: MyInterface;

How do I properly implement this interface, I tried the following but I think its wrong

myOtherInterface = {
    someProperty  = (x, y) => x + y,
     public a = doSomething(x, y) => 'a';
}

I also try to implement this in a call with the following code and get the error

class myClass implements MyInterface {
    public a: number;
    public someProperty: (x, y) => 1;
    public anotherProperty: number = 4;
    public anothermethod: (x: number, y: string) => string = (x, y) => y;
    doSomething(source: string, subString: string): boolean {
        let result = source.search(subString);
        return result > -1;
    }
}

In the class it says the call signature cannot be matched to the one given in MyInterface.

Upvotes: 0

Views: 29

Answers (2)

Esteban Morales
Esteban Morales

Reputation: 1618

Here is an example. Followed the one from the TypeScriptLang docs

interface MyInterface {
(x: number, y: string): string;
someProperty: (x: number, y: number) => number;
anotherProperty: number
}
let myOtherInterface = <MyInterface> function (x, y) { };
myOtherInterface.anotherProperty = 1;
myOtherInterface.someProperty = (x, y) => { return 0 }

Upvotes: 0

artem
artem

Reputation: 51719

There is no language construct in TypeScript that allows to directly implement call signature. Call signatures were added to type system as a way to express types for existing javascript code, to enable typechecking TypeScript code that calls existing javacsript implementation.

That said, one can always use Object.assign to implement such "hybrid" object:

interface MyInterface {
    (x: number, y: string): string;
    someProperty: (x: number, y: number) => number;
    anotherProperty: number
}

function impl(x: number, y: string): string {
    return 'q';
}

let myOtherInterface: MyInterface = Object.assign(impl, {
    someProperty: (x: number, y: number) => 2,
    anotherProperty: 3
});

Upvotes: 2

Related Questions