【问题标题】:How to call js function from a typescript-file?如何从打字稿文件中调用 js 函数?
【发布时间】:2019-07-09 08:12:19
【问题描述】:

我有一个包含 ajaxcall 的函数的 javascript 文件。我试图从我的打字稿文件中调用该函数。我猜是因为我没有声明类型但我不确定如何写这个?

我尝试添加一些类型声明,但 Visual Studio 仍然抱怨 getJsonNoCache。我收到错误

“错误 TS2339 (TS) 属性 'getJsonNoCache' 不存在于类型 '{ postJson(url: string, command: any, onSuccess?: any, onError?: any): 空白; getJson(url: string, query: any, onSuccess?: any, onError?: 任何):无效; }'。”

这是我的 javascript 文件,它作为捆绑包包含在我的网站中。

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",
  });
};

这是我的 ts 文件中我试图调用该函数的函数。

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;
    }));
  });
};

【问题讨论】:

    标签: javascript typescript


    【解决方案1】:

    最简单的方法是将scp.network 断言为any 类型,以使转译器跳过检查scp.network 的属性:

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

    如果你想让它更正确的类型,你可以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;
      };
    };
    

    上面的代码告诉 TypeScript 转译器你的运行时有一个全局变量 scp 这样的类型,然后转译器可以从声明中判断并为你检查类型的正确性。

    【讨论】:

      猜你喜欢
      • 2016-09-12
      • 1970-01-01
      • 1970-01-01
      • 2019-06-13
      • 2016-11-27
      • 1970-01-01
      • 2022-11-26
      • 2021-11-23
      • 1970-01-01
      相关资源
      最近更新 更多