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.
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).
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();
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With