Do we really have to OOPsify everything in TypeScript?

89
June 10, 2019, at 5:30 PM

I have joined a new company and here they have created classes for just about everything, even for the unrelated utility functions.

Consider this:

export default class Utils {
static method1()
static method2()
static method3()
}

vs

export const method1 = () => {}
export const method2 = () => {}
export const method3 = () => {}

Is there any specific advantage one gets by encapsulating the independent methods inside a class? Which is the recommended way for a scalable code base?

Answer 1

This is a common misconception about Typescript. Typescript does not mean you have to use classes. Typescript is Javascript with types. Write your code as you would in Javascript, add types where necessary, and you should be fine.

If you want to take advantage of classes (an ES2015 feature not necessarily a Typescript feature) Typescript will help you have strong types for the classes. But you don't need classes to write good Typescript.

The reasons this misconception probably appeared is that the early demos always showed classes as they were still not in most browsers and needed down-compilation and everyone wanted them. This lead people to the false impression that Typescript works best with classes. But this is definitely not so.

In your particular case I would actually argue it is a bad use of classes. Static classes are an invention for languages that do not allow functions to live anywhere else but in a class. In Javascript the module can encapsulate such static methods as well as any class and is a more Javascript oriented way to do things.

READ ALSO
I want to reverse the function [on hold]

I want to reverse the function [on hold]

I want to reverse this functionOn default, it's set to editmode=off and the function turns it on

63
Callback is not a function for update in Node JS

Callback is not a function for update in Node JS

begginer in Javascript and Node Js hereWhile trying to do my first, simple update function, i got the error :

38
Download pdf in the mobile version of the application

Download pdf in the mobile version of the application

When you click on the button, the pdf file should download to the phoneIn chrome, he downloads without problems

58
Taking two mathrandom values and adding them on loop

Taking two mathrandom values and adding them on loop

I have to make a game of dice where I add the values of both the dice and give the sumYou get another turn if both the dice end up on the same number (such as 2 and 2 which is 4) then you roll the dice again and the 2 new numbers get added to the previous...

65