I am writing a JQuery plugin in TypeScript.
I have an implementation of a class Foo.ts
//Foo.ts
export class Foo {}
I have installed @types/jquery
and the completions for that work fine.
Now I would like to declare a function onto the JQuery
type, which I can do with a types.d.ts
file like so:
//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
.
//types.d.ts
//import {Foo} from './Foo';
interface JQuery {
bar(): Foo;
}
Gives me a red line under 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
//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. 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?
Additionally, can this work so that when I import this module into another project the types for JQuery
are merged correctly?
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:
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.