7

I'm making a jquery widget with widget factory typed in typescript. How to provide a good intellisense without having to write .d.ts ?

ex:

/*mywidget.ts*/

$.widget("ui.mywidget", {
    options: {
        myoption: ""
    },
    doSomething: function () {
        this._hasDoSomething = true;
        /*do doSomething*/
    },
    hasDoSomething: function (): bool {
        return <bool>this._hasDoSomething;
    }
});

/*mywidget.d.ts*/
interface MyWidgetOptions {
    myoption: string;
}

interface MyWidget extends Widget, MyWidgetOptions {}

interface NLIB { 
    mywidget: MyWidget;
}

interface JQuery {
    mywidget(): JQuery;
    mywidget(methodName: string): JQuery;
    mywidget(options: MyWidgetOptions): JQuery;
    mywidget(optionLiteral: string, optionName: string): any;
    mywidget(optionLiteral: string, options: MyWidgetOptions): any;
    mywidget(optionLiteral: string, optionName: string, optionValue: any): JQuery;
}

interface JQueryStatic {
    nlib: NLIB;
}


/// <reference path="teste.d.ts" />
$(".teste").mywidget({
    myoption: "asdadds"
});

Too boring to write .d.ts for each plugin. Any alternative ?

note: If I don't include a mywidget.d.ts this code will no compile and I will not have intellisense:

///<reference path="path/to/jqueryui-1.9.d.ts"/>
$(".teste").mywidget({ 
    myoption: "asdadds"
});

/* compiler out: ... the property 'mywidget' does not exist on value of type 'JQuery' */

Abraão Alves
  • 803
  • 1
  • 8
  • 14
  • 1
    I believe I share the motivation for this question. I **love** typescript, but I wish it had a good answer for a typescript-"native" DOM manipulation library that could be extended to build out typescript-native UI widgets (like auto-complete). I understand why the JQuery UI Widget Factory (which I also loved, pre-typescript) is a bad match here, but what more typescripty solution is possible instead? – Jason Kleban Nov 06 '13 at 16:53

2 Answers2

11

The DefinitelyTyped project on GitHub provides definition files for most of the popular JavaScript libraries.

All you need to do is download the file you need and reference it in your code like:

///<reference path="path/to/jqueryui-1.9.d.ts"/>
thomaux
  • 19,133
  • 10
  • 76
  • 103
ryan
  • 6,541
  • 5
  • 43
  • 68
  • If I don't include a mywidget.d.ts this code will no compile and I will not have intellisense: /// $(".teste").mywidget({ myoption: "asdadds" }); /* compiler out: ... the property 'mywidget' does not exist on value of type 'JQuery' */ – Abraão Alves Dec 26 '12 at 12:43
  • So your viewModel would just have something like this `///` `import * as $ from "jquery"`? – azulBonnet Jan 29 '18 at 16:59
0

If you do not want a .d.ts file, just use the declare keyword before your interface. For an example, see my answer at https://stackoverflow.com/a/16967239/1859442

Community
  • 1
  • 1
Benjamin
  • 1,165
  • 7
  • 19