TypeScriptModules and namespaces
Export and import functions in TypeScript
1 Export add and subtract, then import them
easyWrite a module exporting two functions, one adding two numbers and one subtracting them. Import both into another file and use them.
Stuck? Three hints, smallest first
- 1. A named export is just
exportin front of the declaration. - 2. In modern TypeScript the import path keeps the
.jsextension even though the file is.ts. - 3. Anything without
exportis private to its own file. That is the default, and it is a good one.
The real answer, across 2 files. Type-checked by the compiler at build time; not runnable in a browser, because a panel cannot contain import or export.
// Two named exports. Everything else in this file stays private.
export function add(a: number, b: number): number {
return a + b;
}
export function subtract(a: number, b: number): number {
return a - b;
}
// Not exported, so no other file can reach it.
function unused(): void {}
import { add, subtract } from './maths.js';
console.log(add(2, 3)); // 5
console.log(subtract(10, 4)); // 6
// This would be an error, because `unused` was never exported:
// import { unused } from './maths.js';
const same = (a: unknown, b: unknown): boolean =>
JSON.stringify(a) === JSON.stringify(b);
function test(name: string, got: unknown, want: unknown): void {
console.log(
(same(got, want) ? 'ok ' : 'FAIL ') + name +
(same(got, want) ? '' : ` got ${JSON.stringify(got)}, want ${JSON.stringify(want)}`)
);
}
// The same idea without module syntax, so it can run here. An object literal
// is the closest runnable stand-in for a module: named things on the outside,
// and anything not attached to it stays private.
const maths = {
add(a: number, b: number): number { return a + b; },
subtract(a: number, b: number): number { return a - b; },
};
// Destructuring an object is exactly what `import { add } from ...` feels like.
const { add, subtract } = maths;
console.log(add(2, 3));
console.log(subtract(10, 4));
test('add', add(2, 3), 5);
test('subtract', subtract(10, 4), 6);
test('add is commutative', add(2, 3), add(3, 2));
test('subtract is not', subtract(10, 4) === subtract(4, 10), false);
test('both came off the one object', typeof maths.add, 'function');
Output
Two blocks, and the reason is worth knowing. The file pair above is the real answer and the compiler checked it. The runnable block below cannot use import, because this page runs each panel inside a function and module syntax is only legal at the top level of a file. Notice that const { add, subtract } = maths reads almost exactly like the import — that is not a coincidence, it is what a named import does.