Veit's Blog

Hej! đź‘‹ Welcome to my curated space of insights on software development and the tapestry of life.

Write your own TypeScript definition files

2016-08-01

Last Year I wrote a blog post about TypeScript and jQuery. I introduced TSD, a manager for TypeScript definition files. TSD, or Typings as TSD is deprecated now, contains nearly thousand definition files. But what if you want to use your own library or a library that has no definition file yet? You could write it yourself. It’s not that hard. I will show you an really simple example.

I created a new Angular 2.0 Project with the Angular CLI. The Angular team switched to TypeScript so it fits perfectly in this example. I added a JavaScript file with a simple function and a tiny class (or what JavaScript devs call classes ;)).

function invokeJavaScript() {
  alert('Hello from JavaScript function.')
}



function Person(name){
  this.name = name;
}
Person.prototype.speak = function(){
  alert("Howdy, my name is " + this.name);
};

I’ve copied that file named creepy-javascript.js into the public folder and referenced it in the main HTML file. Also I created a folder own in the folder typings and created the file creepy-javascript.d.ts. This file contains the TypeScript definitions. Add your typings path to index.d.ts and you’re ready.

declare function invokeJavaScript(): void

declare function Person(name: string): void

declare namespace Person {
  export function speak(): void;
}

As you may see, exporting the function is very easy. To create a object of type Personit’s important to export the JavaScript function as return type void. I also declared a namespace for Person. This is not indispensable, but it’s necessary for having IntelliSense in WebStorm.

Now you are able to use your old JavaScript libraries in TypeScript.

invokeJavaScript();

var person = new Person("Walter White")
person.speak();