Peter Olson
Peter Olson

Reputation: 143037

How can I import an external file with TypeScript?

I have a node app that has a string of requires, like this:

var express = require('express'),
    router = require('./router'),
    data = require('./data');

This code works without changes, but how can I take full advantage of TypeScript modules? Just using

import data = module("./data")

will tell me

The name ''./data'' does not exist in the current scope

How can I import an external file with TypeScript?

Upvotes: 8

Views: 11626

Answers (1)

chuckj
chuckj

Reputation: 29625

The example,

http://www.typescriptlang.org/Samples/#ImageBoard

contains a file called node.d.ts which shows how to declare the types for an existing node.js module.

TypeScript requires the module be declared for you use to import syntax. This is typically provided in a .d.ts file but can be included in the same file. An example this might look like,

declare module "./data" {
    function getData(): number;
}

import data = module("./data");

var myData = data.getData();

In a .d.ts file the declare keywords is implied and can be omitted.

Upvotes: 5

Related Questions