1

In Typescript, can I define an interface function object with another interface as such below? I'm trying to define the object I'm going to use in my Ajax function.

But with this code I'm getting an error:

Error:(22, 1) TS2346: Supplied parameters do not match any signature of call target.

The error is set on instance.

interface IXHR {
    Ajax(ajax: IAjax): string;
}

interface IAjax {
    method: string;
    url: string;
    async: boolean;
    callback?: (data: string) => void;
}

class XHR implements IXHR {
    public Ajax(ajax: IAjax) {
        return ajax.url;
    }

    constructor() {}
}

let instance = new XHR();

instance.Ajax('GET', 'URL', true);
3
  • 1
    your method Ajax as defined in IXHR takes one argument, while you tried to call it with your instance with 3 arguments Commented Mar 5, 2016 at 14:44
  • It cannot use the IAjax interface then? I'll have to write all the arguments inside the Ajax function as such: Ajax(method: string, url: string, async: boolean, callback?: () => void): string; The other way just seem more sleek :) Commented Mar 5, 2016 at 14:48
  • I'll try to write a more complete answer to your question Commented Mar 5, 2016 at 14:50

1 Answer 1

1

Your method Ajax as defined in IXHR takes one argument, while you tried to call it with your instance with 3 arguments.

Your instance call, if you want it to comply with your interfaces, should look like:

instance.Ajax({method: 'GET', url: 'URL', async: true});

Another option is to implement the IAjax interface, and using that implementation:

interface IXHR {
    Ajax(ajax: IAjax): string;
}

interface IAjax {
    method: string;
    url: string;
    async: boolean;
    callback?: (data: string) => void;
}

class Ajax implements IAjax {
    constructor(public method: string, public url: string, public async: boolean, public callback?) {

    }
}

class XHR implements IXHR {
    public Ajax(ajax: IAjax) {
        return ajax.url;
    }

    constructor() {}
}

let instance = new XHR();
let iAjax: IAjax = new Ajax('GET', 'URL', true);
instance.Ajax(iAjax);
Sign up to request clarification or add additional context in comments.

1 Comment

This is great. Thanks for your answer. It just doesn't seem as pretty as i thought it would. But my aha-moment has to be the arguments, I was trying to pass 3, but never thought of it to be an object, aha! :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.