How to import a js library without definition file in typescript file

tune2fs picture tune2fs · Apr 3, 2014 · Viewed 45.4k times · Source

I want to switch from JavaScript to TypeScript to help with code management as our project gets larger. We utilize, however, lots of libraries as amd Modules, which we do not want to convert to TypeScript.

We still want to import them into TypeScript files, but we also do not want to generate definition files. How can we achieve that?

e.g. The new Typescript file:

/// <reference path="../../../../definetelyTyped/jquery.d.ts" />
/// <reference path="../../../../definetelyTyped/require.d.ts" />
import $ = require('jquery');
import alert = require('lib/errorInfoHandler');

Here, lib/errorInfoHandler is an amd module included in a huge JavaScript library that we do not want to touch.

Using the above code produces the following errors:

Unable to resolve external module ''lib/errorInfoHandler'' 
Module cannot be aliased to a non-module type.

This should actually produce the following code:

define(["require", "exports", "jquery", "lib/errorInfoHandler"], function(require, exports, $, alert) {
...

}

Is there a way to import a JavaScript library into TypeScript as an amd Module and use it inside the TypeScript file without making a definition file?

Answer

Code Novitiate picture Code Novitiate · Jan 13, 2015

A combination of the 2 answers given here worked for me.

//errorInfoHandler.d.ts
declare module "lib/errorInfoHandler" {
   var noTypeInfoYet: any; // any var name here really
   export = noTypeInfoYet;
}

I'm still new to TypeScript but it looks as if this is just a way to tell TypeScript to leave off by exporting a dummy variable with no type information on it.

EDIT

It has been noted in the comments for this answer that you can achieve the same result by simply declaring:

//errorInfoHandler.d.ts
declare module "*";

See the github comment here.