Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import external definitions

With Typescript, is there a way to import just the types from an external module?

Basically I just want one module to know the typings from another (to power Intellisense), but without the import being emitted in JavaScript. I want to do this because the module in question may or may not have been loaded - i.e. there isn't a hard dependency, but I want to have some typed code that runs and uses the module if it is there.

Hope this is clear.

like image 509
Barguast Avatar asked Feb 08 '15 13:02

Barguast


2 Answers

You can use a definition file along with a reference comment, which makes the types available without adding any import statements (such as require or define).

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

You can automatically generate definition files during compilation, although for your purposes you'll probably want to hand-crank a custom one (depends on how you want to use it - the automatic one will expect to be imported).

Example Code

ModuleA.ts

class ExampleOne {
    doSomething() {
        return 5;
    }
}

export = ExampleOne;

ModuleB.ts

class ExampleTwo {
    doSomething() {
        return 'str';
    }
}

export = ExampleTwo;

Intended use:

import B = require('moduleb');

var a = new ExampleOne();
var b = new B();

To make this work, you would create your ModuleA.d.ts:

ModuleA.d.ts

declare class ExampleOne {
    doSomething(): number;
}

And then reference it like so:

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

import B = require('moduleb');

var a = new ExampleOne();
var b = new B();
like image 105
Fenton Avatar answered Nov 01 '22 07:11

Fenton


I don't know if it answers your question, but you can add a type definitions file:

/** mytype.d.ts */
interface MyType {
  prop1: number,
  prop2: string
}

export default MyType

and import it in both of your modules like this:

/** module1.ts */
import MyType from './mytype.d'

//use
let myVar: MyType
like image 31
Michael Zelensky Avatar answered Nov 01 '22 07:11

Michael Zelensky