TypeScript在命名空间下扩展JQuery [英] TypeScript extend JQuery under Namespace
本文介绍了TypeScript在命名空间下扩展JQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试通过TypeScript中的函数扩展默认的JQuery
接口和默认的对象jQuery
I'm trying to extend the default JQuery
interface and the default object jQuery
by a function in TypeScript
代码
/// <reference path="jquery.d.ts" />
namespace MyNameSpace {
var $ = jQuery;
export interface JQuery {
test(options: Object): JQuery;
}
$.fn.test = function(options: Object): JQuery {
if (this.length === 0) {
console.log('Error!');
return this;
}
console.log(options);
return this;
}
export var testBody = function() {
jQuery('body').test({ 'HELLO': 'TEST' });
}
}
问题
现在,我在控制台中运行以下代码:
tsc -m amd -t ES5 Test.ts -d
Now I'm running the following code in my console:
tsc -m amd -t ES5 Test.ts -d
我收到此错误:Test.ts(17,19): error TS2339: Property 'test' does not exist on type 'JQuery'.
有什么解决办法吗?
推荐答案
这对我有用:
/// <reference path="typings/jquery/jquery.d.ts" />
interface JQuery {
test(options: Object): JQuery;
}
namespace MyNameSpace {
var $ = jQuery;
$.fn.test = function(options: Object): JQuery {
if (this.length === 0) {
console.log('Error!');
return this;
}
console.log(options);
return this;
};
export var testBody = function() {
jQuery('body').test({ 'HELLO': 'TEST' });
}
}
第二种解决方法
/// <reference path="typings/jquery/jquery.d.ts" />
namespace MyNameSpace {
interface JQueryX extends JQuery {
test(options: Object): JQuery;
}
$.fn.test = function(options: Object): JQuery {
if (this.length === 0) {
console.log('Error!');
return this;
}
console.log(options);
return this;
};
export var testBody = function() {
let a:JQueryX = <JQueryX>$('body');
a.test({ 'HELLO': 'TEST' });
// OR
(<JQueryX>$('body')).test({ 'HELLO': 'TEST' });
}
}
您可以通过一些重构使testBody
更好.
You can make the testBody
nicer by some refactoring.
这篇关于TypeScript在命名空间下扩展JQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文