TypeScript - Error calling jQuery getJSON() function

3.6k Views Asked by At

I am using TypeScript 1.7.5 and the latest jQuery type definition. The following call to $.getJSON() fails with "error TS2346: Supplied parameters do not match any signature of call target"

let url: string = api + '/orgs/' + orgname + '/repos?per_page=100';
$.getJSON(url, function(repos: Repo[]) {
    ...
});

Repo is defined as:

export interface Repo {
    name: string;
    stargazers_count: number;
    forks_count: number;
}

The type definition for getJSON() is:

getJSON(url: string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any): JQueryXHR;

What am I missing?

Update

I found that the error is really coming from chaining a call to error(), which is perfectly legal in regular jQuery. If I remove this call to error() the error goes away. Any idea how I could handle the error from getJSON() in TypeScript?

interface Repo {
    name: string;
    stargazers_count: number;
    forks_count: number;
}
var url = "/echo/json/";

$.getJSON(url, (data: any, textStatus: string, jqXHR: JQueryXHR) => {
    var repos: Repo[] = data;
    //...
    alert(JSON.stringify(repos));
})
.error(function() {
    callback([]);
});
1

There are 1 best solutions below

5
On BEST ANSWER

I think this can help:

$.getJSON(url, (data: any, textStatus: string, jqXHR: JQueryXHR) => {
    var repos: Repo[] = data;
    //...
});

Please check the jsfiddle.

Update 1.

You should use "fail" to process errors:

interface Repo {
    name: string;
    stargazers_count: number;
    forks_count: number;
}
var url = "/echo/json/";

$.getJSON(url, (data: any, textStatus: string, jqXHR: JQueryXHR) => {
    var repos: Repo[] = data;
    //...
    alert(JSON.stringify(repos));
})
.fail(function() {
    alert("error!");
    //callback([]);
});