TypeScript export imported interface
I use AMD modules and I want to hide a complex interface behind one file that loads several other files and chooses what to expose and how. It works, I use this solution but it feels kinda ugly, mostly with the interfaces.
import Types = require('./message-types');
import MessageBaseImport = require('./message-base');
export interface IMessage extends Types.IMessage {} // This is an interface
export var MessageBase = MessageBaseImport; // This is a class
Usage:
import Message = require('message');
import { * } as Message from 'message'; // Or with ES6 style
var mb = new Message.MessageBase(); // Using the class
var msg: Message.IMessage = null; // Using the interface
Any better solutions out there? I don't want to put everything into a single file but I want to import
a single file.
There is an export import syntax for legacy modules, and a standard export format for modern ES6 modules:
// export the default export of a legacy (`export =`) module
export import MessageBase = require('./message-base');
// export the default export of a modern (`export default`) module
export { default as MessageBase } from './message-base';
// when '--isolatedModules' flag is provided it requires using 'export type'.
export type { default as MessageBase } from './message-base';
// export an interface from a legacy module
import Types = require('./message-types');
export type IMessage = Types.IMessage;
// export an interface from a modern module
export { IMessage } from './message-types';
Some more examples besides #c-snover's answer from here. You can put them together.
import 'jquery'; // import a module without any import bindings
import $ from 'jquery'; // import the default export of a module
import { $ } from 'jquery'; // import a named export of a module
import { $ as jQuery } from 'jquery'; // import a named export to a different name
import * as crypto from 'crypto'; // import an entire module instance object
export var x = 42; // export a named variable
export function foo() {}; // export a named function
export default 42; // export the default export
export default function foo() {}; // export the default export as a function
export { encrypt }; // export an existing variable
export { decrypt as dec }; // export a variable as a new name
export { encrypt as en } from 'crypto'; // export an export from another module
export * from 'crypto'; // export all exports from another module
// (except the default export)
In my case particularly, I had to 'declare' the interface instead of exporting it.
declare interface IFluxStoreSyncOptions{
namespacedKey: string;
}
In order to use the interface as a type in another file like so:
export function FluxStoreSync(options: IFluxStoreSyncOptions){
}
This way you don't have to export and import the interface.