[英]How to call js function from a typescript-file?
I have a javascript-file with a function that contains an ajaxcall. 我有一个javascript文件,其中包含一个包含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
. 我尝试添加一些类型声明,但Visual Studio仍然抱怨
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; }'."
“错误TS2339(TS)属性'getJsonNoCache'在类型'{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. 这是我的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",
});
};
Here is the function in my ts-file where im trying to call the function. 这是我的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;
}));
});
};
The easiest way is assert scp.network
as type any
to make transpiler skip checking for the properties of scp.network
: 最简单的方法是断言
scp.network
类型any
使transpiler跳过检查的属性scp.network
:
(scp.network as any).getJsonNoCache(...)
If you want to make it more type correctness, you can declare
type for scp: 如果你想让它更加类型正确,你可以为scp
declare
类型:
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. 上面的代码告诉TypeScript转换器,你的运行时有一个像这样的类型的全局变量
scp
,然后转换器可以从声明中判断并检查类型的正确性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.