Reputation: 10665
I want to add a property someString
to the JQueryStatic
interface so I can access it with $.someString
.
In index.ts
, I have this code:
interface JQueryStatic {
someString: string;
}
$.someString = "string";
$
is of type JQueryStatic
, however I get the following error:
Property 'someString' does not exist on type 'JQueryStatic'.
Upvotes: 3
Views: 2964
Reputation: 13196
You can make use of an ambient type declaration that extends the jQuery type declarations like this:
declare interface JQueryStatic {
someString: string;
}
put it in a .d.ts
file somewhere in your code and make sure it's included (or not excluded) in your tsconfig.json
.
Why does this work?
The declare
bit is what makes this "ambient" - as in "there exists somewhere a JQueryStatic
which has a someString
member". TypeScript is smart and picks up that there is also another JQueryStatic
ambient declaration elsewhere (in your case the jQuery typings and "merges" them together in a single JQueryStatic
interface declaration.
Upvotes: 4
Reputation: 11710
The existing type information for $
is in a declaration file (which you probably downloaded). If you'd like to merge your new interface declaration into the existing interface, put your declaration into a jquery-extensions.d.ts
file:
interface JQueryStatic {
someString: string;
}
If necessary, add a reference path to this new file at the top of your code:
/// <reference path="../path/to/jquery-extensions.d.ts" />
Upvotes: 2