I have a module that depends on Backbone
. I have a backbone.d.ts
definition but TypeScript doesn't seem to want to compile my module unless my
import Backbone = module("backbone")
actually points to a valid backbone module as opposed to a definition file. I am using AMD loaded modules and have a requirejs shim defined for backbone.
Is there a workaround besides creating a phoney backbone.ts module definition?
Update: A side effect of the solution is that code such as this no longer works because the module no longer exists. It needs to exist because of the requirejs shim. The only workaround I know of is to have two .d.ts files. One for the file using backbone as an import that does not include the declare module
bit. The other for using a /// <reference
that does include the declare module
line.
/// <reference path="../dep/backbone/backbone.d.ts" />
interface IApi {
version: number;
Events: Backbone.Events;
}
The TypeScript language has changed a fair bit since this original answer.
For example, to import an external module you use require
(my original answer had the old module
keyword):
Here is a common use case for importing backbone - using the type information from Definitely Typed:
/// <reference path="scripts/typings/backbone/backbone.d.ts" />
import bb = require('backbone');
Within the type definition, the backbone module is declared for you, which is what allows the import to be valid:
//... lots of code and then...
declare module "backbone" {
export = Backbone;
}
So the original question could be resolved using...
/// <reference path="scripts/typings/backbone/backbone.d.ts" />
import bb = require('backbone');
interface IApi {
version: number;
Events: bb.Events;
}
class Api implements IApi {
public version = 1;
public Events: bb.Events = null;
}
For this code example, this is all that is required - but more often you will want the backbone library loaded at runtime... you can use the (officially experimental) amd-dependency
comment to cause the generated define
function call to include backbone.
/// <reference path="scripts/typings/backbone/backbone.d.ts" />
/// <amd-dependency path="backbone" />
import bb = require('backbone');
interface IApi {
version: number;
Events: bb.Events;
}
class Api implements IApi {
public version = 1;
public Events: bb.Events = null;
}