Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write d.ts file from existing .js file?

Tags:

typescript

I am using typescript and i want to use jquery.steps library to create a wizard from typescript. Right now there is no typed definition file available for jquery.steps. Trying to figure our on how to write a typing file.

like image 622
Sushant Srivastava Avatar asked Aug 05 '14 11:08

Sushant Srivastava


1 Answers

You can always define any object as type any and then call any methods you wish. Of course you would lose the type checking so creating d.ts is probably better but time consuming.

Anyway what you should do is to create file jquery.steps.d.ts in the same folder as jquery.steps.js. Then you must reference jquery.d.ts.

///<reference path="../jquery/jquery.d.ts" />

Now you are ready to start typing...

First you would create interface JQuery and add any methods that extend standard jQuery ($) object. This will be merged with interface JQuery defined in jquery.d.ts and you will be able to call these methods from TypeScript. Method name has to match its name in JavaScript. Parameter names can be changed. Return value must be same as in JavaScript.

1) Definition

interface JQuery {
    testMethod(parameter: string): JQuery;
}

2) Usage

var $: JQuery;
$.testMethod("test");

If any special objects are used, typically settings for a plugin and similar, you must define that as a separate interface. Name of the interace doesn't matter but property names must match its names in JavaScript.

1) Definition

interface IJQueryPluginSettings {
    test: string;
}

interface JQuery {
    initPlugin(settings: IJQueryPluginSettings): JQuery;
}

2) Usage

var $: JQuery;
var settings: IJQueryPluginSettings = <IJQueryPluginSettings> {
    test: "test"
};

$.initPlugin(settings);

With this approach you can cover most of the code. The key is naming of the methods/properties which must match. Also looking at already created d.ts will help you. Look at similar plugins like https://github.com/borisyankov/DefinitelyTyped/blob/master/jquery.joyride/jquery.joyride.d.ts or more complicated https://github.com/borisyankov/DefinitelyTyped/blob/master/jqueryui/jqueryui.d.ts

You do not have to cover all the methods/properties to use it. You can cover only the par of code you wish to call from TypeScript. In case you cover all or most of the jQuery plugin, please upload it to https://github.com/borisyankov/DefinitelyTyped

like image 174
David Bohunek Avatar answered Sep 27 '22 00:09

David Bohunek