我正在尝试通过 TypeScript 中的函数扩展默认的 JQuery
接口(interface)和默认对象 jQuery
代码
/// <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
我收到此错误:Test.ts(17,19):错误 TS2339:属性“test”在类型“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
更好。
关于javascript - TypeScript 在 Namespace 下扩展 JQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33277521/