Simpler Typescript Classes

Ole Ersoy
Aug 17, 2021

Scenario

We need a minimal Typescript class that will store the median of a set of numbers:

Approach

The file Median.ts contains the class.

import { median } from './median';export class Median {
result: number = undefined;
constructor(arr: number[]) {
this.result = median(arr);
}
}

The function computing the median is contained in median.ts . See the demo:

https://stackblitz.com/edit/typescript-2njmx7

Demo

Notice that we have broken off the function median from the class. This allows us to:

  • Easily place the function in a utility library if it’s reused outside of the context of the class.
  • View the class in a more minimal uncluttered form
  • Code tests that are smaller and more focused

--

--