typescript – Modules – exporting and importing – Re-export

Typescript allow to re-export declarations.

//Operator.ts
interface Operator {
    eval(a: number, b: number): number;
}
export default Operator;
//Add.ts
import Operator from "./Operator";
export class Add implements Operator {
    eval(a: number, b: number): number {
        return a + b;
    }
}
//Mul.ts
import Operator from "./Operator";
export class Mul implements Operator {
    eval(a: number, b: number): number {
        return a * b;
    }
}

You can bundle all operations in single library

//Operators.ts
import {Add} from "./Add";
import {Mul} from "./Mul";

export {Add, Mul};

Named declarations can be re-exported using shorter syntax

//NamedOperators.ts
export {Add} from "./Add";
export {Mul} from "./Mul";

Default exports can also be exported, but no short syntax is available. Remember, only one default export per module is possible.

//Calculator.ts
export {Add} from "./Add";
export {Mul} from "./Mul";
import Operator from "./Operator";

export default Operator;

Possible is re-export of bundled import

//RepackedCalculator.ts
export * from "./Operators";

When re-exporting bundle, declarations may be overridden when declared explicitly.

//FixedCalculator.ts
export * from "./Calculator"
import Operator from "./Calculator";
export class Add implements Operator {
    eval(a: number, b: number): number {
        return 42;
    }
}

Usage example

//run.ts
import {Add, Mul} from "./FixedCalculator";

const add = new Add();
const mul = new Mul();

console.log(add.eval(1, 1)); // 42
console.log(mul.eval(3, 4)); // 12

if you want to reproduce, please indicate the source:
typescript – Modules – exporting and importing – Re-export - CodeDay