[英]JQuery plugin typescript definition mixin
I am writing a JQuery plugin in TypeScript. 我在TypeScript中编写一个JQuery插件。
I have an implementation of a class Foo.ts
我有一个Foo.ts
类的Foo.ts
//Foo.ts
export class Foo {}
I have installed @types/jquery
and the completions for that work fine. 我已经安装了@types/jquery
并且工作正常。
Now I would like to declare a function onto the JQuery
type, which I can do with a types.d.ts
file like so: 现在,我想在JQuery
类型上声明一个函数,可以使用types.d.ts
文件执行types.d.ts
操作:
//types.d.ts
interface JQuery {
bar(): string;
}
This works to allow me to do 这可以让我做
//Baz.ts
let result: string = $('#Baz').bar();
However, the return type of bar()
is not string
but should be Foo
. 但是, bar()
的返回类型不是string
而应该是Foo
。
//types.d.ts
//import {Foo} from './Foo';
interface JQuery {
bar(): Foo;
}
Gives me a red line under Foo
[ts] Cannot find name 'Foo'
. 在Foo
[ts] Cannot find name 'Foo'
下给我一个红线。 [ts] Cannot find name 'Foo'
。 If I uncomment the import line, types.d.ts
is happy, but then I then get an error in 如果取消注释导入行, types.d.ts
很高兴,但是随后我得到一个错误
//Baz.ts
let result: string = $('#Baz').bar();
// [ts] Property 'bar' does not exist on type 'JQuery<HTMLElement>'.
It seems the definitions for JQuery
are no longer merging. 看来JQuery
的定义不再合并。 I understand that a types declaration file is not global if it has imports or exports, but then I don't know how to reference types in other files. 我知道类型声明文件如果具有导入或导出,则不是全局的,但是我不知道如何在其他文件中引用类型。
How can I declare an additional function on the JQuery
type whos definition references other types? 如何在谁定义引用其他类型的JQuery
类型上声明其他函数?
Additionally, can this work so that when I import this module into another project the types for JQuery
are merged correctly? 另外,是否可以正常工作,以便在将模块导入另一个项目时可以正确合并JQuery
的类型?
It certainly seems to me like this should be possible. 在我看来,这肯定是可能的。
If you are using a module system then then you must place the extension of JQuery
in the global namespace: 如果使用模块系统,则必须将JQuery
扩展名放在全局名称空间中:
import {Foo} from './Foo';
declare global {
interface JQuery {
bar(): Foo;
}
}
If you are not using a module system then you don't need to use export on the Foo
class and is should work. 如果您不使用模块系统,则无需在Foo
类上使用export,它应该可以工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.