1

I have a javascript-file with a function that contains an ajaxcall. Im trying to call that function from my typescript-file. Im guessing its because I did not declare the types but Im not sure how to write this?

I tried to add some type declarations but Visual Studio still complains about getJsonNoCache. I get the error

"Error TS2339 (TS) Property 'getJsonNoCache' does not exist on type '{ postJson(url: string, command: any, onSuccess?: any, onError?: any): void; getJson(url: string, query: any, onSuccess?: any, onError?: any): void; }'."

Here is my javascriptfile that is included as a bundle to my website.

scp.network.getJsonNoCache = function(url, query, onSuccess, onError, statusCodeEvents) {
  $.ajax({
    contentType: 'application/json; charset=utf-8',
    type: "GET",
    url: url,
    data: query,
    cache: false,
    statusCode: {
      401: function() {
        window.location = '/';
      },
      405: function() {
        rfq.mainModel.errorHeader('Information');
      }
    },
    success: function(data) {
      if (onSuccess !== undefined)
        onSuccess(data);
    },
    error: function(data) {
      if (onError !== undefined) {
        onError(data);
      }
    },
    dataType: "json",
  });
};

Here is the function in my ts-file where im trying to call the function.

this.getUsers = (callback: any, text: string) => {
  if (text.length < 2) {
    callback([]);
    return;
  }

  scp.network.getJsonNoCache(audit.queries.GET_INTERNAL_USERS, {
    searchText: text,
    maxCount: 10,
    roleId: 5
  }, function(data: any) {
    this.queriedUsers = data.users;
    console.log(data.users);

    callback(_.map(this.queriedUsers, function(user: any) {
      return user.name;
    }));
  });
};

1 Answer 1

3

The easiest way is assert scp.network as type any to make transpiler skip checking for the properties of scp.network:

(scp.network as any).getJsonNoCache(...)

If you want to make it more type correctness, you can declare type for scp:

declare var scp: {
  network: {
    getJsonNoCache: (
      url: string,
      query: Record<string, string | number>,
      onSuccess?: (data: any) => void,
      onError?: (error: any) => void,
    ) => void;
  };
};

The above code tell TypeScript transpiler that your runtime has a global variable scp which type like this, then transpiler can tell from the declaration and check the type correctness for you.

Sign up to request clarification or add additional context in comments.

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.