8. Dependency Injection in TypeScript
Activity 8.01: DI-Based Calculator
Solution:
In this activity, we will build a basic calculator that utilizes DI to evaluate mathematical expressions, as well as logging its output to either the console or a file:
- To start things off, define the basic building block of our calculator – an operator. This is defined via an interface, which actual implementations can rely on:
export interface Operator { readonly symbol: string; evaluate(a: number, b: number): number; }
You need to create this file in the
src/interfaces
folder and save it asoperator.interface.ts
. - Next, implement the first operator – the addition operator. This will be a class that implements the
Operator
interface:import { Operator } from '../interfaces/operator.interface'; export class AddOperator implements Operator { readonly symbol = '+'; ...