TypeScriptModules and namespaces
Create a namespace in TypeScript
6 A MathUtility namespace
easyWrite a namespace holding functions for add, subtract, multiply and divide. Call them through the namespace name.
Stuck? Three hints, smallest first
- 1. Inside a namespace, only what you mark
exportis reachable from outside it. - 2. A namespace compiles to a plain object, so it runs here with no adaptation.
- 3. Namespaces are largely superseded by modules. Know them for reading older code.
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)}`)
);
}
namespace MathUtility {
// Exported: reachable as MathUtility.add
export function add(a: number, b: number): number { return a + b; }
export function subtract(a: number, b: number): number { return a - b; }
export function multiply(a: number, b: number): number { return a * b; }
export function divide(a: number, b: number): number {
if (b === 0) throw new RangeError('cannot divide by zero');
return a / b;
}
// Not exported, so MathUtility.round is not available outside.
function round(n: number): number { return Math.round(n); }
export function average(values: number[]): number {
if (values.length === 0) return 0;
return round(values.reduce((n, v) => n + v, 0) / values.length);
}
}
console.log(MathUtility.add(2, 3));
console.log(MathUtility.subtract(10, 4));
console.log(MathUtility.multiply(6, 7));
console.log(MathUtility.divide(20, 4));
console.log(MathUtility.average([1, 2, 3, 4]));
let refused = '';
try { MathUtility.divide(1, 0); } catch (err) { refused = (err as RangeError).message; }
// MathUtility.round(1.5); // error: Property 'round' does not exist
test('add', MathUtility.add(2, 3), 5);
test('subtract', MathUtility.subtract(10, 4), 6);
test('multiply', MathUtility.multiply(6, 7), 42);
test('divide', MathUtility.divide(20, 4), 5);
test('divide by zero refused', refused, 'cannot divide by zero');
test('average uses the private helper', MathUtility.average([1, 2, 3, 4]), 3);
test('an empty list averages to zero', MathUtility.average([]), 0);
Output
round is deliberately not exported, which shows that a namespace has a real inside and outside just as a module does. Do learn namespaces, because plenty of older code and many .d.ts files use them — but for new code, a module is almost always the right choice.